<?php
/**
 * Created by PhpStorm.
 * User: 跳梁
 * Date: 2015/11/16
 * Time: 14:11
 */
define('QR_IMG_URL', 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=');

//文章链接url
define('CONTENTURL', 'http://wx9db859ac98c33a73.wx.mboxone.com/wx/call.html?module=micontent&method=getMiContentDetail&');
//背景图片
//define('BACKGROUNDIMG', 'http://oss.mboxone.com/20180330/image/50/1522377165948628.png');
define('BACKGROUNDIMG', 'http://oss.mboxone.com/20180423/image/50/1524473828250578.jpg');
define('DOWNPICURL', 'http://oss.mboxone.com/20180726/image/50/1532578498579388.png');
//文章id
define('CONTENTID', 6522);
//cid
define('CID', 117);
class community{

    public static function getIndex($qid){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
//        if(!isMicroMessengerUserAgent()){
//            Output::instance()->resultCode(1,"不是微信浏览器！");
//            return;
//        }
        $uid = Session::$user['userId'];
        $userName= Session::$user['userName'];
        $customerId = Session::$user['customerId'];
        log::write("mh_打印getindex中session.".json_encode(Session::$user));
        Session::switchCustomer(0);
        $quanModel = M("miyouquan");
        $userModel = M("quan_user");
        $contentModel = M("micontent");
        $miuStatistics = M("miu_statistics");
        $salesourceStatistics = M("salesource_statistics");
        $mimall = M("mimall_user");
        $mivendorModel = M("mivendor");
        Session::switchCustomer($customerId);
        $personCount = $userModel->where("qid=".$qid." and deleted = 0 and status = 1")->count();
        $topicCount = $contentModel->where("qid=".$qid." and type=1 and deleted = 0")->count();
        $quanInfo = $quanModel
            ->where("id=".$qid)->find();
        $quanInfo["mallId"] = 0;
        $quanInfo["refereeUrl"] = self::setRefereeUrl($qid,$uid,$quanInfo["refereeUrl"]);
        $selfInfo = $userModel->alias("a")
            ->join("wx_".$customerId."_user b on a.uid=b.id")
            ->join("wx_".$customerId."_user_weixin_info c on b.id=c.userId")
            ->join("wx_quan_team d on a.teamId=d.id and d.deleted=0")
            ->field("a.identity,c.*,a.uid,a.uid as miUId,a.teamId,d.teamLeader,a.miCoins,a.totalRevenue,a.isSaleSource,a.configJson,b.fullName,b.phone,b.qrcodeUrl,a.isMiUDeliver")
            ->where("a.uid =$uid and a.qid = $qid and a.deleted =0 and a.status = 1")
            ->find();
        log::write("mh_打印selfInf信息".json_encode($selfInfo));
        if(!$selfInfo['uid']){
            Output::instance()->resultCode(1,"无访问权限");
            return;
        }
        //查询数据看板数据
        if ($selfInfo['isSaleSource']){
            $selfData = R('MiYouQuan/StatisData',array($customerId, $qid, $uid, 2));
        }else{
            $selfData = R('MiYouQuan/StatisData',array($customerId, $qid, $uid, 1));
        }
        $selfDataInfo = [
            [
                "type" =>1,
                "descript" => '推荐好友',
                "number" => (empty($selfData["friendCount"]) ? 0 : $selfData["friendCount"]). '人'
            ],
            [
                "type" =>2,
                "descript" => '分享浏览人数',
                "number" => (empty($selfData["shareUv"]) ? 0 : $selfData["shareUv"]) . '人'
            ],
            [
                "type" =>3,
                "descript" => '总收入',
                "number" => round($selfInfo["totalRevenue"],2). '元'
            ],
            [
                "type" =>4,
                "descript" => '账户余额',
                "number" =>  round($selfInfo["miCoins"],2). '元'
            ],
            [
                "type" =>5,
                "descript" => '普通订单数',
                "number" => (empty($selfData["buyOrderCount"]) ? 0 : $selfData["buyOrderCount"]) . '单'
            ],
            [
                "type" =>6,
                "descript" => '普通订单销售额',
                "number" => (empty($selfData["buyOrderPrice"]) ? 0 : $selfData["buyOrderPrice"]) . '元'
            ],
            [
                "type" =>7,
                "descript" => '积分订单数',
                "number" => (empty($selfData["pointOrderCount"]) ? 0 : $selfData["pointOrderCount"]) . '单'
            ],
            [
                "type" =>8,
                "descript" => '积分订单销售额',
                "number" => (empty($selfData["pointOrderPrice"]) ? 0 : $selfData["pointOrderPrice"]) . '积分'
            ]
            ,
            [
                "type" =>9,
                "descript" => '营销订单数',
                "number" => (empty($selfData["formOrderCount"]) ? 0 : $selfData["formOrderCount"]) . '单'
            ],
            [
                "type" =>10,
                "descript" => '营销订单销售额',
                "number" => (empty($selfData["formOrderPrice"]) ? 0 : $selfData["formOrderPrice"]) . '元'
            ],
            [
                "type" =>11,
                "descript" => '分享次数',
                "number" => (empty($selfData["shareCount"]) ? 0 : $selfData["shareCount"]). '次'
            ]

        ];

        //侯佳注释于2018-03-17，此段代码导致rds的cpu使用过高且没发现有用处
//        if($quanInfo['isSaleSource']){
//            $result['fansCount'] = $mimall->where("qid = $qid and saleSource=$uid and cId=".$quanInfo['cId'])->count();
//        } else if($quanInfo['parentRefereeAward']>0){
//			 $result['fansCount'] = $userModel->alias("a")
//            ->join("wx_quan_user b on a.uid=b.refereeUid and a.qid = b.qid and b.status=1 and b.deleted=0")
//            ->join("wx_quan_user c on b.uid=c.refereeUid and c.qid = b.qid and c.status=1 and c.deleted=0")
//            ->join("inner join wx_mimall_user d on a.qid=d.qId and (a.uid=d.miUid or b.uid=d.miUid or b.uid=d.uId
//            or c.uid=d.miUid or c.uid=d.uId)")
//            ->where("a.qid = $qid and a.uid=$uid and (d.uId<>$uid or d.uId is NULL) and d.cId=".$quanInfo['cId'])
//            ->group("d.id")
//            ->field("d.id")
//            ->select();
//            $result['fansCount'] = count($result['fansCount']);
//		}else if($quanInfo['refereeAward']>0){
//			$result['fansCount'] = $userModel->alias("a")
//            ->join("wx_quan_user b on a.uid=b.refereeUid and a.qid = b.qid and b.status=1 and b.deleted=0")
//            ->join("inner join wx_mimall_user d on a.qid=d.qId and (a.uid=d.miUid or b.uid=d.miUid or b.uid=d.uId)")
//            ->where("a.qid = $qid and a.uid=$uid and (d.uId<>$uid or d.uId is null) and d.cId=".$quanInfo['cId'])
//            ->group("d.id")
//            ->field("d.id")
//            ->select();
//            $result['fansCount'] = count($result['fansCount']);
//		}else{
//            $result['fansCount'] = $userModel->alias('a')
//                ->join('inner join wx_mimall_user b on (a.uid=b.uId or b.miUid=a.refereeUid) and a.qid=b.qId')
//                ->where("a.refereeUid = $uid and (b.uId<>$uid or b.uId is null) and a.deleted=0 and a.status=1 and a.qid=$qid and b.cId=".$quanInfo['cId'])
//                ->group("b.id")
//                ->field("b.id")->select();
//            $result['fansCount'] = count($result['fansCount']);
//		}
        //LP修改
        $vendors = $quanModel->alias("a")
//            ->join("inner join wx_quan_vendor b on a.id = b.quanId")
            ->join("inner join wx_mivendor c on a.vid=c.id")
            ->field("vid as ids")
            ->where("a.id=$qid")
            ->find();
        $jsonMenu = json_decode($quanInfo["config"],true);
        $quanInfo["config"] = $jsonMenu;
        $contentList = $contentModel->alias("a")
            ->join("inner join wx_mishare b on if(a.type = 0 or a.type is null,b.module='micontent',b.module='topic') and a.id=b.moduleId")
            ->join("inner join wx_mishare_top c on b.id = c.sid")
            ->join("left join wx_".$customerId."_user d on a.uId=d.id")
            ->join("left join wx_".$customerId."_user_weixin_info e on d.id = e.userId")
            ->field("a.*,b.shareCount,b.viewCount,b.praiseCount,e.nickname,e.headimgurl,b.id as sid,c.id as isTop")
            ->where("b.module='micontent' and a.deleted = 0 and c.qid = $qid and a.vId in (".$vendors["ids"].")")
            ->group("a.id")
            ->order("c.createTime desc")
            ->select();
        foreach($contentList as $key=>$content){
            if($content["picUrl1"]){
                $contentList[$key]["picUrl1"] = explode(",",$content["picUrl1"]);
            }
            $vendorInfo = $mivendorModel->where(['id' => $content['vId']])->find();
            $contentList[$key]["headimgurl"]=$vendorInfo["logo"];
            $contentList[$key]["nickname"]=$vendorInfo["name"];
        }
        $result["contentList"] = $contentList;
        $result["facebox"] = self::getFacebox();
        $result["personCount"]=$personCount;
        $result["topicCount"]=$topicCount;
        $result["selfInfo"]=$selfInfo;
        //$result["indexMenu"]=$jsonMenu;
        $result["quanInfo"]=$quanInfo;
        $result["selfDataInfo"]=$selfDataInfo;
        Output::instance()->module("community","index")->object($result);
    }
    //LP修改
    public static function contentList($qid,$start=0,$limit=20){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $userName=Session::$user['userName'];
        $customerId = Session::$user['customerId'];
        $uid = Session::$user['userId'];
        Session::switchCustomer(0);
        $userModel = M("quan_user");
        $contentModel = M("micontent");
        $commentModel = M("mishare_comment");
        $praiseModel = M("mishare_praise");
        $mivendorModel = M("mivendor");
        $quanModel = M("miyouquan");
        Session::switchCustomer($customerId);
        $selfInfo = $userModel->where("uid=$uid and qId = $qid")->find();
        $vendors = $quanModel->alias("a")
//            ->join("inner join wx_quan_vendor b on a.id = b.quanId")
            ->join("inner join wx_mivendor c on a.vid=c.id")
            ->field("vid as ids")
            ->where("a.id=$qid")
            ->find();
        $contentList = $contentModel->alias("a")
            ->join("inner join wx_mishare b on if(a.type = 0 or a.type is null,b.module='micontent',b.module='topic') and a.id=b.moduleId")
            ->join("left join wx_mishare_top c on b.id = c.sid and c.qid = $qid")
            ->join("left join wx_".$customerId."_user_weixin_info e on a.uId = e.userId")
            ->field("a.*,b.shareCount,b.commentCount,b.viewCount,b.praiseCount,e.nickname,e.headimgurl,b.id as sid,c.id as isTop")
            ->where("(((a.qid = $qid and type=1)) or ((b.module='micontent' and c.id is NULL and a.vId in (".$vendors["ids"].")))) and a.deleted = 0 and b.cid is NULL")
            ->group("a.id")
            ->order("c.createTime desc,a.updateTime desc")
            ->limit($start,$limit)
            ->select();
        $contentCountInfo = $contentModel->alias("a")
            ->join("inner join wx_mishare b on if(a.type = 0 or a.type is null,b.module='micontent',b.module='topic') and a.id=b.moduleId")
            ->join("left join wx_mishare_top c on b.id = c.sid and c.qid = $qid")
            ->join("left join wx_".$customerId."_user_weixin_info e on a.uId = e.userId")
            ->field("a.*,b.shareCount,b.commentCount,b.viewCount,b.praiseCount,e.nickname,e.headimgurl,b.id as sid,c.id as isTop")
            ->where("(((a.qid = $qid and type=1)) or ((b.module='micontent' and c.id is NULL and a.vId in (".$vendors["ids"].")))) and a.deleted = 0 and b.cid is NULL")
            ->group("a.id")
            ->order("c.createTime desc,a.updateTime desc")
            ->select();
        foreach($contentList as $key=>$content){
            if($content["picUrl1"]){
                $contentList[$key]["picUrl1"] = explode(",",$content["picUrl1"]);
            }
            $sid = $content["sid"];
            $commentList = $commentModel->alias("a")
                ->join("left join wx_".$customerId."_user_weixin_info c on a.uId = c.userId")
                ->join("left join wx_".$customerId."_user b on a.uId=b.id")
                ->field("a.*,b.fullName,c.nickname")
                ->where("a.sId=$sid and a.qId = $qid and a.deleted = 0")
                ->order("a.createTime asc")
                ->select();
            foreach($commentList as $i => $comment){
                $commentList[$i]["comment"] = html_entity_decode($comment["comment"]);
                $replyId = $comment["replyId"];
                foreach($commentList as $j =>$reply){
                    if($replyId == $reply["id"]){
                        $commentList[$i]["replyName"] = $reply["nickname"];
                    }
                }
            }
            $contentList[$key]["comment"] = $commentList;
            if($content["type"]==1){
                $contentList[$key]["content"] = html_entity_decode($content["content"]);
                $Guid = new Guid();
                $guid = $Guid->toString();
                $visitParam=new StdClass();
                $visitParam->guid=$guid;
                $visitParam->sId=$sid;
                $visitParam->miUId=$selfInfo["uid"];
                $visitParam->qId=$selfInfo["qid"];
                $visitParam->fromPage="micontent_detail";
                $visitId = Module::callModule("quan", Session::$user,"addVisit", $visitParam);
//                $shareModel->query("update wx_mishare set viewCount=viewCount+1 where id = ".$sid);
            }
            if(!$content["type"]){
                $vid = $content["vId"];
                $vendorInfo = $mivendorModel->where("id=$vid")->find();
                $contentList[$key]["headimgurl"]=$vendorInfo["logo"];
                $contentList[$key]["nickname"]=$vendorInfo["name"];
            }
            $praiseList = $praiseModel->alias("a")
                ->join("wx_".$customerId."_user b on a.uid=b.id")
                ->join("wx_".$customerId."_user_weixin_info c on b.id = c.userId")
                ->where("a.sId=".$sid)
                ->order("a.createTime asc")
                ->field("b.fullName,c.nickname,c.openid")
                ->select();
            $contentList[$key]["selfPraise"] = 0;
            foreach($praiseList as $k=>$praise){
                if($praise["openid"]==$userName){
                    $contentList[$key]["selfPraise"] = 1;
                }
            }
            $contentList[$key]["praise"] = $praiseList;
        }
        $result["content"] = $contentList;
        $result['total'] = count($contentCountInfo);
        Output::instance()->object($result);
    }
    public static function getFansCount($qid){
        $uid = Session::$user['userId'];
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $quanModel = M("miyouquan");
        $quanuser = M("quan_user");
        Session::switchCustomer($customerId);
        $quanInfo = $quanModel->where("id=".$qid)->find();
        if($quanInfo['parentRefereeAward']>0){
            //一级粉丝数
            $onelev = $quanuser->alias("a")
                ->join("wx_quan_user c on c.refereeUid = a.uid and c.qid = a.qid and c.status=1 and c.deleted=0")
                ->join("inner join wx_mimall_user b on a.qid = b.qId and (c.uid=b.uId or a.uid=b.miUid)")
                ->where("a.qid = $qid and a.uid = $uid and (b.uId<>$uid or b.uId is NULL) and a.status=1 and a.deleted=0 and b.cId=".$quanInfo['cId'])
                ->group("b.id")
                ->field("b.id")
                ->select();
            $onelev = count($onelev);
            //二级粉丝数
            $secondLev = $quanuser->alias("a")
                ->join("wx_quan_user b on a.qid=b.qid and b.refereeUid=a.uid and b.deleted=0 and b.status=1")
                ->join("inner join wx_mimall_user c on a.qid=c.qId and (b.uid=c.uId or (a.uid=c.miUid and (a.uid<>c.uId or c.uId is NULL)))")
                ->where("a.qid=$qid and a.refereeUid=$uid and a.status=1 and a.deleted=0 and c.cId=".$quanInfo['cId'])
                ->field("c.id")
                ->group("c.id")
                ->select();
            $secondLev = count($secondLev);
            //三级粉丝数
            $threeLev = $quanuser->alias("a")
                ->join("inner join wx_quan_user c on c.refereeUid=a.uid and a.qid = c.qid and c.deleted=0 and c.status=1")
                ->join("wx_mimall_user b on a.qid = b.qId and (c.uid=b.miUid)")
                ->where("a.refereeUid = $uid and a.qid = $qid and a.status = 1 and a.deleted=0 and b.cId=".$quanInfo['cId'])
                ->group("b.id")
                ->field("b.id")
                ->select();
            $threeLev = count($threeLev);
        }else if($quanInfo['refereeAward']>0){
            //一级粉丝数
            $onelev = $quanuser->alias("a")
                ->join("wx_quan_user c on c.refereeUid = a.uid and c.qid=a.qid and c.status=1 and c.deleted=0")
                ->join("inner join wx_mimall_user b on a.qid = b.qId and (c.uid=b.uId or a.uid=b.miUid)")
                ->where("a.qid = $qid and a.uid = $uid and (b.uId<>$uid or b.uId is null) and a.status=1 and a.deleted=0 and b.cId=".$quanInfo['cId'])
                ->group("b.id")
                ->field("b.id")
                ->select();
            $onelev = count($onelev);
            //二级粉丝数
            $secondLev = $quanuser->alias("a")
                ->join("inner join wx_mimall_user b on a.qid =b.qId and a.uid=b.miUid and (b.uId <> a.uid or b.uId is null)")
                ->where("a.refereeUid=$uid and a.qid = $qid and a.status=1 and a.deleted=0 and b.cId=".$quanInfo['cId'])
                ->group("b.id")
                ->field("b.id")
                ->select();
            $secondLev = count($secondLev);
            $threeLev =0;
        }else{
            //一级粉丝数
            $onelev = $quanuser->alias("a")
                ->join("inner join wx_mimall_user b on a.qid = b.qId and a.uid=b.miUid")
                ->where("a.qid = $qid and a.uid = $uid and (b.uId<>$uid or b.uId is null) and a.status=1 and a.deleted=0 and b.cId=".$quanInfo['cId'])
                ->group("b.id")
                ->field("b.id")
                ->select();
            $onelev = count($onelev);
        }
        $result['onelev'] = $onelev;
        $result['secondLev'] = $secondLev;
        $result['threeLev'] = $threeLev;

        Output::instance()->object($result);
    }

    public static function getComment($sid,$qid){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $commentModel = M("mishare_comment");
        Session::switchCustomer($customerId);
        $commentList = $commentModel->alias("a")
            ->join("inner join wx_".$customerId."_user b on a.uId = b.id")
            ->join("left join wx_".$customerId."_user_weixin_info c on b.id = c.userId")
            ->field("a.*,b.fullName,c.nickname,c.openid")
            ->where("a.sId=$sid and a.qId = $qid and a.deleted = 0")->select();
        foreach($commentList as $i => $comment){
            $commentList[$i]["comment"] = html_entity_decode($comment["comment"]);
            $replyId = $comment["replyId"];
            foreach($commentList as $j =>$reply){
                if($replyId == $reply["id"]){
                    if($reply["fullName"]){
                        $commentList[$i]["replyName"] = $reply["fullName"];
                    }else{
                        $commentList[$i]["replyName"] = $reply["nickname"];
                    }
                }
            }
        }
        Output::instance()->object($commentList);
    }
    public static function saveComment($sId,$uId,$qid,$comment,$replyId){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $commentModel = M("mishare_comment");
        $shareModel = M("mishare");
        Session::switchCustomer($customerId);
        $comment = urldecode($comment);
        preg_match_all('/\[(.[^\[]*)\]/',$comment,$newStr);
        foreach($newStr[0] as $key=>$str){
            $faceboxInfo = self::getFaceboxInfo($str);
            if($faceboxInfo){
                $url = $faceboxInfo->url;
                $img = '<img src="'.C("SERVER_NAME")."/".$url.'" alt="'.$newStr[1][$key].'">';
                $comment = str_replace($str,$img,$comment);
            }
        }
        $data["sId"] = $sId;
        $data["comment"] = $comment;
        $data["uId"] = $uId;
        $data["status"] = 1;
        $data["deleted"] = 0;
        $data["createTime"] = date("Y-m-d H:i:s");
        $data["updateTime"] = date("Y-m-d H:i:s");
        $data["qId"] = $qid;
        $data["replyId"] = $replyId;
        $result = $commentModel->add($data);
        $shareResult = $shareModel->query("update wx_mishare set commentCount=commentCount+1 where id = ".$sId);
        if($result){
            //获取所有的评论信息
            $commentList = $commentModel->alias("a")
                ->join("left join wx_".$customerId."_user_weixin_info c on a.uId = c.userId")
                ->join("left join wx_".$customerId."_user b on a.uId=b.id")
                ->field("a.*,b.fullName,c.nickname")
                ->where("a.sId=$sId and a.qId = $qid and a.deleted = 0")
                ->order("a.createTime asc")
                ->select();
            foreach($commentList as $i => $comment){
                $commentList[$i]["comment"] = html_entity_decode($comment["comment"]);
                $replyId = $comment["replyId"];
                foreach($commentList as $j =>$reply){
                    if($replyId == $reply["id"]){
                        $commentList[$i]["replyName"] = $reply["nickname"];
                    }
                }
            }
            //输出评论内容
            Output::instance()->object([
                'code'=>0,
                'msg'=>'ok',
                'data'=>$commentList,
            ]);
        }else{
            Output::instance()->resultCode(code_sql_error);
        }
    }
    public static function deletedComment($id,$sId){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $commentModel = M("mishare_comment");
        $shareModel = M("mishare");
        Session::switchCustomer($customerId);
        $data["deleted"] = 1;
        $data["createTime"] = date("Y-m-d H:i:s");
        $result = $commentModel->where("id=".$id)->save($data);
        $shareResult = $shareModel->query("update wx_mishare set commentCount=commentCount-1 where id = ".$sId);
        if($result){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }
    }
    public static function addPraise($sId,$qid,$uId){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        if($uId==4640){
            Output::instance()->resultCode(1,"操作过于频繁");
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $pariseModel = M("mishare_praise");
        $shareModel = M("mishare");
        Session::switchCustomer($customerId);
        $pariseInfo = $pariseModel->where("qid=$qid and sid=$sId and uid=$uId")->find();
        if($pariseInfo){
            $resultCode = new stdClass();
            $resultCode->code=2;
            $resultCode->msg='已赞';
            Output::instance()->object($resultCode);
            return;
        }
        $data["uid"] = $uId;
        $data["sId"] = $sId;
        $data["qid"] = $qid;
        $data["createTime"] = date("Y-m-d H:i:s");
        $pariseId = $pariseModel->add($data);
        $shareResult = $shareModel->query("update wx_mishare set praiseCount=praiseCount+1 where id = ".$sId);
        $praiseList = $pariseModel->alias("a")
            ->join("wx_".$customerId."_user b on a.uid=b.id")
            ->join("wx_".$customerId."_user_weixin_info c on b.id = c.userId")
            ->where("a.sId=".$sId)
            ->order("a.createTime asc")
            ->field("b.fullName,c.nickname,c.openid,a.createTime")
            ->select();
        if($pariseId){
            $out = new stdClass();
            $out->code = 0;
            $out->id = $pariseId;
            $out->self = $praiseList;
            Output::instance()->object($out);
        }else{
            Output::instance()->resultCode(code_sql_error);
        }
    }
    public static function deletedPraise($uId,$sId,$qid){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $pariseModel = M("mishare_praise");
        $shareModel = M("mishare");
        Session::switchCustomer($customerId);
        $pariseInfo = $pariseModel->where("uid=".$uId." and sId = ".$sId." and qid = ".$qid)->find();
        $pariseResult = $pariseModel->where("id=".$pariseInfo["id"])->delete();
        $shareResult = $shareModel->query("update wx_mishare set praiseCount=praiseCount-1 where id = ".$sId);
        if($pariseResult){
            $praiseList = $pariseModel->alias("a")
                ->join("wx_".$customerId."_user b on a.uid=b.id")
                ->join("wx_".$customerId."_user_weixin_info c on b.id = c.userId")
                ->where("a.sId=".$sId)
                ->order("a.createTime asc")
                ->field("b.fullName,c.nickname,c.openid,a.createTime")
                ->select();
            $out = new stdClass();
            $out->code = 0;
            $out->id = $pariseInfo["id"];
            $out->self = $praiseList;
            Output::instance()->object($out);
        }else{
            Output::instance()->resultCode(code_sql_error);
        }
    }
    public static function setTop($sid,$qid){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $userName=Session::$user['userName'];
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $shareTopModel = M("mishare_top");
        Session::switchCustomer($customerId);
        $userModel = M("user");
        $userInfo = $userModel->where("userName = '".$userName."'")->find();
        $topInfo = $shareTopModel->where("qid=$qid and sid=$sid")->find();
        if($topInfo){
            $resultCode = new stdClass();
            $resultCode->code=2;
            $resultCode->msg='已经存在置顶';
            Output::instance()->object($resultCode);
            return;
        }
        $uId = $userInfo["id"];
        $data["qid"] = $qid;
        $data["sid"] = $sid;
        $data["createTime"] = date("Y-m-d H:i:s");
        $data["uid"] = $uId;
        $result = $shareTopModel->add($data);
        if($result){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }
    }
    public static function cancelTop($sid,$qid){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $userName=Session::$user['userName'];
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $shareTopModel = M("mishare_top");
        Session::switchCustomer($customerId);
        $userModel = M("user");
        $userInfo = $userModel->where("userName = '".$userName."'")->find();
        $uId = $userInfo["id"];
        $condition["sid"]=array("eq",$sid);
        $condition["qid"]=array("eq",$qid);
        $result = $shareTopModel->where($condition)->delete();
        if($result){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }
    }
    public static function deleted($id){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $userName=Session::$user['userName'];
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $contentModel = M("micontent");
        Session::switchCustomer($customerId);
        $data["deleted"] = 1;
        $data["updateTime"] = date("Y-m-d H:i:s");
        $condition["id"] = array("eq",$id);
        $result = $contentModel->where($condition)->save($data);
        if($result){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }
    }
    public static function post($picUrl,$content,$qid,$uid){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $contentModel = M("micontent");
        $shareBaseModel=M("mishare");
        Session::switchCustomer($customerId);
        preg_match_all('/\[(.[^\[]*)\]/',$content,$newStr);
        foreach($newStr[0] as $key=>$str){
            $faceboxInfo = self::getFaceboxInfo($str);
            if($faceboxInfo){
                $url = $faceboxInfo->url;
                $img = '<img src="'.C("SERVER_NAME")."/".$url.'" alt="'.$newStr[1][$key].'" width="24" height="24">';
                $content = str_replace($str,$img,$content);
            }
        }
        $picUrls = explode(",",$picUrl);
        $data["fromCustomerId"] = $customerId;
        $data["picUrl"] = $picUrls[0];
        $data["picUrl1"] = $picUrl;
        $data["content"] = $content;
        $data["publishTime"] = date("Y-m-d H:i:s");
        $data["createTime"] = date("Y-m-d H:i:s");
        $data["updateTime"] = date("Y-m-d H:i:s");
        $data["uId"] = $uid;
        $data["qid"] = $qid;
        $data["type"] = 1;
        $contentId = $contentModel->add($data);
        //分享基础表
        $shareBaseData=array(
            "module" => "topic" ,
            "moduleId" => $contentId ,
            "shareCount" => 0 ,
            "viewCount" => 0 ,
            "praiseCount" => 0 ,
            "commentCount" => 0 ,
            "createTime"=> date("Y-m-d H:i:s"),
            "deleted" => 0
        );
        $resultBase=$shareBaseModel->add($shareBaseData);
        if($contentId&&$resultBase){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }
    }
    //用户推广 LP修改
    public static function userPromotion($qid){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $quanModel = M("miyouquan");
        Session::switchCustomer($customerId);
        $vendorList = $quanModel->alias("a")
//            ->join("inner join wx_quan_vendor b on a.id = b.quanId")
            ->join("inner join wx_mivendor c on a.vid=c.id")
            ->join("inner join wx_customer_user d on c.fromCustomerUserId=d.id")
            ->join("inner join wx_mimall e on d.customerId=e.fromCustomerId")
            ->field("e.id,e.logo,e.name,d.customerId")
            ->where("a.id=$qid and d.agent='vendor' and e.deleted=0")
            ->group("d.customerId")
            ->select();
        $result["vendorList"] = $vendorList;
        Output::instance()->object($result);

    }
    //通过推广招募来的用户列表
    public static function recruitUserList($cid,$qid,$type,$start=0,$limit=20){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $result = self::userList($cid,$qid,$start,$limit,$type);
        Output::instance()->object($result);
    }
    public static function userList($cid,$qid,$start,$limit,$type=0){
        $uId = Session::$user['userId'];
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $mimallModel = M("mimall_user");
        $mallStoreModel = M("");
        Session::switchCustomer($customerId);
        $storeInfo = $mallStoreModel->table("wx_".$cid."_module_mall_store")->find();
        $Guid = new Guid();
        $guid = $Guid->toString();
        $mllResult = self::getTpl($storeInfo["storeurl"]);
        $param = $mllResult["param"];
        $param->qId = $qid;
        $param->miUId = $uId;
        $param->fromGuid = $guid;
        $mallUrl = $mllResult["url"].urlencode(json_encode($param));
        if($type){
            $where = "(a.fromModule='qrcode')";
            $userList = $mimallModel->alias("a")
                ->join("wx_".$cid."_user_weixin_info b on a.openid=b.openid")
                ->where("a.cId=$cid and a.qId = $qid and a.miUid = $uId and ".$where)
                ->field("b.nickname,b.headimgurl,a.createTime")
                ->limit($start,$limit)
                ->order("a.createTime desc")
                ->select();
            $count = $mimallModel->alias("a")
                ->join("wx_".$cid."_user_weixin_info b on a.openid=b.openid")
                ->where("a.cId=$cid and a.qId = $qid and a.miUid = $uId and ".$where)
                ->count();
        }else{
            $where = "(a.fromModule<>'qrcode')";
            $userList = $mimallModel->alias("a")
                ->join("inner join wx_".$customerId."_user b on a.uid=b.id")
                ->join("wx_".$customerId."_user_weixin_info c on c.userId=b.id")
                ->where("a.qId = $qid and a.miUid = $uId and ".$where)
                ->field("c.nickname,c.headimgurl,a.createTime")
                ->limit($start,$limit)
                ->order("a.createTime desc")
                ->select();
            $count = $mimallModel->alias("a")
                ->join("inner join wx_".$customerId."_user b on a.uid=b.id")
                ->join("wx_".$customerId."_user_weixin_info c on c.userId=b.id")
                ->where("a.qId = $qid and a.miUid = $uId and ".$where)
                ->count();
        }
        $result["count"] = $count;
        $result["mallUrl"]=$mallUrl;
        $result["userList"] = $userList;
        return $result;
    }
    //销售源好友列表
    public static function saleSourceFansList($qid,$start=0,$limit=10,$search=null,$register=null,$order=null){
        $uId = Session::$user['userId'];
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $friendsAliasModel = M('friends_alias');
        $mimallModel = M("mimall_user");
        $quanUser = M("quan_user");
        Session::switchCustomer($customerId);
        $weixin = M('user_weixin_info');

        $where_friend['a.saleSource'] = $uId;
        $where_friend['a.cId'] = $customerId;
        $where_friend['a.qId'] = $qid;
        $where_friend["a.uId"] = array('neq', $uId);


        //增加好友的注册情况筛选
        $strSql = '';
        if ($register == 'yes'){
            $sql = "a.uId = a.miUid";
            $strSql .= $sql;
        }else if ($register == 'no'){
            $sql = "a.uId <> a.miUid";
            $strSql .= $sql;
        }
        //增加排序条件
        if (empty($order) || ($order == 'time')){
            $order = 'a.createTime desc';
        }else{
            if ($order == 'people'){
                $order = 'st.friendCount desc';
            }else if ($order == 'share'){
                $order = 'st.shareUv desc';
            }else if ($order == 'order'){
                $order = 'st.orderCount desc';
            }
        }
        //增加搜索条件
        if (!empty($search)){
            if (!empty($strSql)){
                $sql = ' AND';
            }else{
                $sql = '';
            }
            $sql .= ' ( c.fullName LIKE  "%' . $search . '%" ) OR (d.nickname LIKE "%' . $search . '%") OR ( c.phone LIKE "%' . $search . '%")';
            $strSql .= $sql;
        }
        // 最后拼接SQL
        if (!empty($strSql)) {
            $where_friend['_string'] = $strSql;
        }

        $list = $mimallModel->alias("a")
            ->join("wx_quan_user b on a.qId=b.qid and a.uId=b.uid and b.deleted=0")
            ->join("wx_".$customerId."_user c on a.uId=c.id")
            ->join("wx_".$customerId."_user_weixin_info d on c.id=d.userId")
            ->join("wx_miu_statistics st on a.uId = st.uid and st.cid=".$customerId)
            ->field("c.status,d.nickname,d.headimgurl,b.id as child,c.email,c.city,c.province,c.birthday,c.phone,c.wxNumber,c.fullName,a.uid,a.createTime,b.id as quid,a.refereeUid as upRefereeUid,a.miUid")
            ->where($where_friend)
            ->order($order)
            ->limit($start,$limit)
            ->select();
        //获取上级推荐人信息
        if (!empty($list)){
            foreach ($list as $key=>$value) {
                if ($value['quid']){
                    $where_referee['userId'] = $value['upRefereeUid'];
                }else{
                    $where_referee['userId'] = $value['miUid'];
                    $list[$key]['upRefereeUid'] = $value['miUid'];
                }
                // $where_referee['qid'] = $qid;
                // $where_referee['deleted'] = 0;
                // $list[$key]['refereeInfo'] = $quanUser->where($where_referee)->getField("nickName");
                $list[$key]['refereeInfo'] = $weixin->where($where_referee)->getField("nickname");
                //侯佳2018-07-12添加，好友备注名称
                $aliasName = $friendsAliasModel->where(['cid' => $customerId, 'userId' => $uId, 'friendId' => $value['uid']])->getField('alias');
                $list[$key]['aliasName'] = $aliasName;

            }
        }

        if($list){
            $count = $mimallModel->alias("a")
                ->join("wx_quan_user b on a.qId=b.qid and a.uId=b.uid and b.deleted=0")
                ->join("wx_".$customerId."_user c on a.uId=c.id")
                ->join("wx_".$customerId."_user_weixin_info d on c.id=d.userId")
                ->join("wx_miu_statistics st on a.uId = st.uid and st.cid=".$customerId)
                ->where($where_friend)
                ->count();
            $return['code'] = 0;
            $return['msg'] = '好友列表返回';
            $return['data'] = $list;
            $return['total'] = $count;
            Output::instance()->object($return);
        }else{
            $return['code'] = 0;
            $return['msg'] = '好友列表返回';
            $return['data'] = [];
            $return['total'] = 0;
            Output::instance()->object($return);
        }
    }
    public static function fansList($mallId,$uid,$qid,$start,$limit,$page){
        $uId = Session::$user['userId'];
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $mimallModel = M("mimall_user");
        $modle = M("");
        $quanUser = M("quan_user");
        $miyouquan = M("miyouquan");
        Session::switchCustomer($customerId);
        $page?"":$page=0;
        $quanInfo = $miyouquan->where("id=$qid")->field("refereeAward,parentRefereeAward,cId")->find();
        if($quanInfo['parentRefereeAward']>0){
            $maxLev = 3;
        }else if($quanInfo['refereeAward']>0){
            $maxLev = 2;
        }else{
            $maxLev = 1;
        }
        if($uid==$uId){
            $level=1;
        }else{
            $quanInfo = $quanUser->alias("a")
                ->join("wx_quan_user b on a.refereeUid = b.uid and b.qid = a.qid and b.status=1 and b.deleted=0")
                ->join("wx_miyouquan c on a.qid = c.id")
                ->where("a.qid = $qid and a.uid = $uid")
                ->field("a.refereeUid,b.refereeUid as parRefereeUid,c.cId")
                ->find();
            if($quanInfo['refereeUid']==$uId){
                $level=2;
            }else{
                $level = 3;
            }
        }
        $mallCId = $quanInfo["cId"];
        //获得所有的一级范围内的用户
        $userList = $quanUser->alias("a")
            ->join("inner join wx_mimall_user b on a.qid = b.qId and a.uid=b.uId")
            ->join("wx_".$mallCId."_user c on b.uId = c.id")
            ->field("a.nickname,a.headimgurl,b.createTime,a.uid,c.status")
            ->where("a.qid=$qid and a.refereeUid=$uid and a.uid<>$uid and a.status=1 and a.deleted=0 and b.cId=$mallCId")
            ->order("b.createTime desc")
            ->limit($start,$limit)
            ->select();
        if($userList){
            $listCount =count($userList);
            $page += $listCount;
            $start = 0;
        }else{
            $listCount = 0;
            if($start>0) {
                $start -= $page;
            }
        }
        if($listCount<$limit||!$userList){
            $limit = $limit-$listCount;
            $mallList = $mimallModel->alias("a")
                ->where("a.qid=$qid and a.miUid = $uid and (a.uId<>$uid or a.uId is NULL) and a.cId=$mallCId")
                ->field("a.createTime,a.openid,a.uId")
                ->limit($start,$limit)
                ->order("a.createTime desc")
                ->select();
            if(!$userList){
                $userList =$mallList;
            }else if($mallList){
                $userList = array_merge($userList,$mallList);
            }
        }
        foreach($userList as $key=>$value){
            if($value["uid"]){
                $childUid = $value["uid"];
                if($level==$maxLev-1){
                    $count = $mimallModel->where("qId=$qid and miUid=$childUid and uId<>$childUid")->count();
                    $userList[$key]["child"]=$count;
                }else{
                    //$count=$mimallModel->where("qId=$qid and refereeUid=$uid and uId<>$uid and uId<>$childUid and (miUid=$childUid or uId=miUid)")->count();
                    $count = $quanUser->alias("a")
                        ->join("inner join wx_mimall_user b on a.qid = b.qId and (b.miUid=a.uid or a.uid=b.uId)")
                        ->where("a.qid = $qid and (a.refereeUid = $childUid or a.uid=$childUid) and (b.uid<>$childUid or b.uid is null) and b.cId=$mallCId")
                        ->count();
                    $userList[$key]["child"]=$count;
                }
            }else{
                $userList[$key]["child"]=0;
                $userInfo = $modle->table("wx_".$mallCId."_user_weixin_info")->alias("b")
                    ->join("wx_".$mallCId."_user c on b.userId = c.id")
                    ->field("b.nickname as nickName,b.headimgurl as headImgUrl,c.status")
                    ->where("b.userId='".$value['uId']."'")
                    ->find();
                $userList[$key]["nickName"]=$userInfo['nickName'];
                $userList[$key]["headImgUrl"]=$userInfo['headImgUrl'];
                $userList[$key]["status"]=$userInfo['status'];
            }
        }
        $result['page']=$page;
        $result['level']=$level;
        $result["userList"] = $userList;
        Output::instance()->object($result);
    }
    //好友个人设置
    public static function personConfig($qid,$phone=null,$qrcode=null,$themeImg=null,$name=null){
        $uId = Session::$user['userId'];
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $quanUser = M("quan_user");
        Session::switchCustomer($customerId);
        $user = M('user');


        //进行背景图的设置添加
        if (!empty($themeImg)){
            $json = $quanUser->where("qid=$qid and uid=$uId and deleted=0 and status =1")->getField("configJson");
            $json?$json = json_decode($json,true):$json=array();
            $json['themeImg'] = $themeImg;
            $result = $quanUser->where("qid=$qid and uid=$uId and deleted=0 and status =1")->setField("configJson",json_encode($json));
        }else{
            //进行用户姓名、手机号、二维码图片的存储
            $save_data['fullName'] = $name;
            $save_data['phone'] = $phone;
            $save_data['qrcodeUrl'] = $qrcode;
            $result = $user->where("id=$uId")->save($save_data);
        }

        if($result!==false){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }
    }
    private static function getTpl($url) {
        $urlParam = strstr($url, 'params');
        if(strstr($urlParam, '%7B')){
            $urlParam = str_replace("%7B", "{", $urlParam);
            $urlParam = strstr($urlParam,"{");
            $url = strstr($url,"%7B",true);
        }
        if(strstr($urlParam, '%7D')){
            $urlParam = str_replace("%7D", "}", $urlParam);
        }
        if(strstr($urlParam, '%7D')){
            $urlParam = str_replace("%7D", "}", $urlParam);
        }
        if(strstr($urlParam, '%22')){
            $urlParam = str_replace("%22", "\"", $urlParam);
        }
        if(strstr($urlParam, '%3A')){
            $urlParam = str_replace("%3A", ":", $urlParam);
        }
        if(strstr($urlParam, '%2C')){
            $urlParam = str_replace("%2C", ",", $urlParam);
        }
        $param= json_decode($urlParam);
        $result["param"] = $param;
        $result["url"] = $url;
        return $result;
    }
    public static function miQrcode($qid,$uId,$self=0,$module,$moduleId){
        !$uId?$uId = Session::$user['userId']:"";
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $quanUser = M("quan_user");
        $qrcodeModel = M("qrcode");
        $productModel = M("module_product");
        $micontentModel = M("micontent");
        $userPosterModel =M("module_user_poster");
        Session::switchCustomer($customerId);
        $MallStoreModel = m('module_mall_store');
        $userInfo = $quanUser->alias("a")
            ->join("inner join wx_".$customerId."_user b on a.uid=b.id")
            ->field("a.nickname,b.fullName,b.userName")
            ->where("a.qid=$qid and a.uid=$uId and a.status=1 and a.deleted=0")->find();
        $posterData = self::getPoster($module,$moduleId);
        if(empty($posterData) && ($module == 'product' || $module == 'micontent')){
            self::getProductCode($module, $moduleId);
        }
        $result = [];
        foreach ($posterData as $key => $value){
            $where['uId'] = $uId;
            $where['posterId'] = $value['id'];
            $qrCodeInfo = $userPosterModel->where($where)->find();
            $userInfo['moduleId'] = $value['moduleId'];
            $userInfo['uid'] = $uId;
            if(!$qrCodeInfo['picUrl']) {
                if (!$qrCodeInfo) {
                    $data = array(
                        "cId" => $customerId,
                        "uId" => $uId,
                        "posterId" => $value['id'],
                        "createTime" => date("Y-m-d H:i:s")
                    );
                    $id = $userPosterModel->add($data);
                    if($value['module'] == 'micontent'){
                        $method = 'getMiContentDetail';
                        $module = 'micontent';
                        $actionName = 'QR_URL';
                        $contentName = $micontentModel->where(['id' => $value['moduleId']])->getField('title');
                        $desc = "文章".$contentName."海报" . $userInfo['fullName'] . "(" . $userInfo['nickname'] . ")";
                    }elseif ($value['module'] == 'product'){
                        $method = 'getProduct';
                        $module = 'product';
                        $actionName = 'QR_URL';
                        $productName = $productModel->where(['id' => $value['moduleId']])->getField('name');
                        $desc = "商品". $productName ."海报" . $userInfo['fullName'] . "(" . $userInfo['nickname'] . ")";
                    }else{
                        $method = 'promotionCode';
                        $module = 'community';
                        $actionName = 'QR_LIMIT_SCENE';
                        $desc = "合伙人" . $userInfo['fullName'] . "(" . $userInfo['nickname'] . ")";
                    }

                    $data = QRCode::add($desc, null, $module, $id, $method, $actionName, '', '',$customerId, $userInfo);
                    $result[$key]['qrImg'] = $data["img"];
                } else {
                    $id = $qrCodeInfo['id'];
                    $module = $value['module'];
                    $qrcode = $qrcodeModel->where("moduleId=$id and module=$module")->find();
                    if(!$qrcode || $qrcode['actionName'] == QR_URL){
                        if($value['module'] == 'micontent'){
                            $method = 'getMiContentDetail';
                            $module = 'micontent';
                            $actionName = 'QR_URL';
                            $contentName = $micontentModel->where(['id' => $value['moduleId']])->getField('title');
                            $desc = "文章".$contentName."海报" . $userInfo['fullName'] . "(" . $userInfo['nickname'] . ")";
                        }elseif ($value['module'] == 'product'){
                            $method = 'getProduct';
                            $module = 'product';
                            $actionName = 'QR_URL';
                            $productName = $productModel->where(['id' => $value['moduleId']])->getField('name');
                            $desc = "商品". $productName ."海报" . $userInfo['fullName'] . "(" . $userInfo['nickname'] . ")";
                        }else{
                            $method = 'promotionCode';
                            $module = 'community';
                            $actionName = 'QR_LIMIT_SCENE';
                            $desc = "合伙人" . $userInfo['fullName'] . "(" . $userInfo['nickname'] . ")";
                        }
                        $data = QRCode::add($desc, null, $module, $id, $method, $actionName, '', '',$customerId, $userInfo);
                        $result[$key]['qrImg'] = $data["img"];
                    }else{
                        if($value['module'] == 'community'){
                            $result[$key]['qrImg'] = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" . $qrcode['ticket'];
                        }else{          /* 此处QR_URL逻辑有问题*/
                            $result[$key]['qrImg'] = $qrCodeInfo['qrcode'];
                        }
                    }
                }




                $result[$key]['id']=$id;
                $result[$key]['customerInfo']=$value;
                $result[$key]['isOld']=0;
            } else{
                $result[$key]['qrImg'] = $qrCodeInfo["picUrl"];
                $result[$key]['isOld']=1;
            }
        }

        if($self){
            return $result;
        }
        Output::instance()->object($result);
    }
    public static function getPromotionCode($qid,$uId,$module,$moduleId){
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $userPosterModel =M("module_user_poster");
        $MallStoreModel = m('module_mall_store');
        Session::switchCustomer($customerId);
        $mallInfo = $MallStoreModel
            ->field("logo,name,qrcodeBack,recommend,qrcodeLocation,qrcodeSize")
            ->find();
        !$uId?$uId = Session::$user['userId']:"";
        $result = self::miQrcode($qid,$uId,1,$module,$moduleId);
        $fileName = time().$uId;
        foreach($result as $k=>$v){
            if(!$v['isOld']) {
                $id=$v['id'];
                $qrImg=$v['qrImg'];
                $customerInfo=$v['customerInfo'];
                if($v['customerInfo']['module'] == 'product' || $v['customerInfo']['module'] == 'micontent'){
                    $fileName = rand(10000, 99999).$fileName;
                    $tempXY = explode('|',$customerInfo['qrcodeLocation']);
                    $tempGW = explode('*',$customerInfo['qrcodeSize']);
                    $qrcodeLocation['x'] = $tempXY[0];
                    $qrcodeLocation['y'] = $tempXY[1];
                    $qrcodeSize['w'] = $tempGW[0];
                    $qrcodeSize['h'] = $tempGW[1];
                    $qrRet = self::createMoreImg($fileName,$qrImg,$v['customerInfo']['posterBack'],$qrcodeLocation,$qrcodeSize,$customerId);
                    @unlink($v['qrImg']);
                    if($qrRet->code){
                        Output::instance()->resultCode(1, $qrRet->msg);
                        return;
                    }
                    $result[$k]['qrImgUrl'] = $qrRet->path;
                    $updateData["picUrl"]= $qrRet->path;
                    $userPosterModel->where("id=$id")->save($updateData);
                }else{
//                    $tempXY = explode('|',$customerInfo['qrcodeLocation']);
//                    $tempGW = explode('*',$customerInfo['qrcodeSize']);
//                    $qrcodeConfig = self::qrcodeConfig($v['customerInfo']['posterBack'],$tempXY,$tempGW);
//                    $qrcodeLocation = $qrcodeConfig['location'];
//                    $qrcodeSize = $qrcodeConfig['size'];
//                    $qrcodeLocation = implode('|', $qrcodeLocation);
//                    $qrcodeSize = implode('*', $qrcodeSize);
                    $out = self::createImage($fileName,$qrImg,$mallInfo["logo"],$mallInfo["name"],$customerInfo["posterBack"],
                        $customerInfo["recommend"],$customerInfo['qrcodeLocation'],$customerInfo['qrcodeSize'],$customerId);
                    if($out && !$out->code){
                        $updateData["picUrl"]=$out->path;
                        $result[$k]['qrImgUrl'] = $out->path;
                        $userPosterModel->where("id=$id")->save($updateData);
                    } else {
                        Output::instance()->resultCode(1,$out->msg);
                        return;
                    }
                }

            }else{
                $result[$k]['qrImgUrl']=$v['qrImg'];
            }
        }
        Output::instance()->module('community','poster')->object(["code"=>0, "results"=>$result]);

    }
    public function createImage($fileName,$qrImg,$vendorLogo,$vendorName,$bgImgUrl,$recommend,$location,$size,$cid=null){
        $fname="vendor_$fileName.png";
        $fileName=LOCAL_PIC_PATH . "$fname";
        if(!$bgImgUrl){
            $bgImgUrl = 'http://oss.mboxone.com/20151217/image/1/1450337390954875.png';
            $img=self::curls($bgImgUrl);
            $img=imagecreatefromstring($img);
            if(!$img) {
                $out1 = new stdClass();
                $out1->code=1;
                $out1->msg="背景图片获取错误，请重试";
                return $out1;
            }
            $imgWidth=imagesx($img);
            $imgHeight=imagesy($img);
            $qrImg=self::curls($qrImg);
            $qrImg=imagecreatefromstring($qrImg);
            if(!$qrImg) {
                $out1=new StdClass();
                $out1->code=1;
                $out1->msg="二维码生成错误，请重试";
                return $out1;
            }
            $qrImgWidth=imagesx($qrImg);
            $qrImgHeight=imagesy($qrImg);
            $qrImgLeft=10;
            $qrImgTop = $imgHeight-$qrImgHeight+65;

            $headImg=self::curls($vendorLogo);
            $headImg=imagecreatefromstring($headImg);
            $headImgWidth=imagesx($headImg);
            $headImgHeight=imagesy($headImg);
            $headLeft = ($imgWidth-250)/2;
            $radius = 50;
            $lt_corner  = self::get_lt_rounder_corner($radius);
            imagecopymerge($headImg, $lt_corner, 0, 0, 0, 0, $radius, $radius, 100);
            $rt_corner  = imagerotate($lt_corner, 180, 0);
            imagecopymerge($headImg, $rt_corner, $headImgWidth - $radius, $headImgHeight - $radius, 0, 0, $radius, $radius, 100);
            imagecopyresampled($img,$headImg,$headLeft,40,0,0,250,250,$headImgWidth,$headImgHeight);
            $fontcolor=imagecolorallocate($img,51,51,51);
            $font=__DIR__."/FZLTHJW.TTF";
            $fontsize=36;
            $fontsize1=22;
            $fontTop = 250+120;
            $fontTop1 = 450;
            $fontBox = imagettfbbox($fontsize, 0, $font, $vendorName);
            imagettftext($img,$fontsize,0,ceil(($imgWidth - $fontBox[2]) / 2),$fontTop,$fontcolor,$font,$vendorName);
            $width = $imgWidth-40;
            $fontcolor1=imagecolorallocate($img,119,119,119);
            $text = self::autowrap($fontsize1, 0,$font, $recommend, $width); // 自动换行处理
            $fontBox1 = imagettfbbox($fontsize1,0,$font,$text);
            imagettftext($img,$fontsize1,0,ceil(($imgWidth - $fontBox1[2]) / 2),$fontTop1,$fontcolor1,$font,$text);
            imagecopyresampled($img,$qrImg,$qrImgLeft,$qrImgTop,0,0,290,290,$qrImgWidth,$qrImgHeight);
            imagejpeg($img,$fileName);
            imagedestroy($img);
            imagedestroy($headImg);
        }else{
            $img=self::curls($bgImgUrl);

            $img=imagecreatefromstring($img);
            if(!$img) {
                $out1 = new stdClass();
                $out1->code=1;
                $out1->msg="背景图片获取错误，请重试";
                return $out1;
            }
            $imgWidth=imagesx($img);
            $imgHeight=imagesy($img);
            $qrImg=self::curls($qrImg);
            $qrImg=imagecreatefromstring($qrImg);
            if(!$qrImg) {
                $out1=new StdClass();
                $out1->code=1;
                $out1->msg="二维码生成错误，请重试";
                return $out1;
            }
            $qrImgWidth=imagesx($qrImg);
            $qrImgHeight=imagesy($qrImg);
            if($size){
                $size = explode("*",$size);
                $sizeW = $size[0];
                $sizeH = $size[1];
            }else{
                $sizeW=220;
                $sizeH=220;
            }
            if($location){
                $location = explode("|",$location);
                $qrImgLeft=$location[0];
                $qrImgTop=$location[1];
            }else{
                $qrImgLeft=$imgWidth/2-110;
                $qrImgTop = $imgHeight/2-110;
            }
            imagecopyresampled($img,$qrImg,$qrImgLeft,$qrImgTop,0,0,$sizeW,$sizeH,$qrImgWidth,$qrImgHeight);
            imagejpeg($img,$fileName);
            imagedestroy($img);
        }
        //开始上传
        if($qrImg) {
            if(file_exists($fileName)){
                $out=R("Upload/uploadLocalFileToOss",array($fname,$fileName));
                if(!$out->code){
                    return $out;
                }
            }
        } else {
            $out=new StdClass();
            $out->code=1;
            return $out;
        }
    }
    function get_lt_rounder_corner($radius) {
        $img     = imagecreatetruecolor($radius, $radius);  // 创建一个正方形的图像
        $bgcolor    = imagecolorallocate($img, 255, 255, 255);   // 图像的背景
        $fgcolor    = imagecolorallocate($img, 0, 0, 0);
        imagefill($img, 0, 0, $bgcolor);
        imagefilledarc($img, $radius, $radius, $radius*2, $radius*2, 180, 270, $fgcolor, IMG_ARC_PIE);
        imagecolortransparent($img, $fgcolor);
        return $img;
    }
    function autowrap($fontsize, $angle, $fontface, $string, $width) {
        // 这几个变量分别是 字体大小, 角度, 字体名称, 字符串, 预设宽度
        $content = "";
        $tempstring = "";
        // 将字符串拆分成一个个单字 保存到数组 letter 中
        for ($i=0;$i<mb_strlen($string);$i++) {
            $letter[] = mb_substr($string, $i, 1,"utf8");
        }
        foreach ($letter as $l) {
            $teststr = $content.$l;
            $testbox = imagettfbbox($fontsize, $angle, $fontface, $teststr);
            // 判断拼接后的字符串是否超过预设的宽度
            if (($testbox[2] > $width) && ($content !== "")) {
                $tempstring .= "\n";
                $content = "";
            }
            $content .= $l;
            $tempstring.=$l;
        }
        return $tempstring;
    }
    public function curls($url, $timeout = '10')
    {
        // 1. 初始化
        $ch = curl_init();
        // 2. 设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        // 3. 执行并获取HTML文档内容
        $info = curl_exec($ch);
        // 4. 释放curl句柄
        curl_close($ch);

        return $info;
    }
    public function newFansMessage($qid,$uid,$userName,$cid){
        Session::switchCustomer(0);
        $user_tab = M("user");
        $quanuser = M("quan_user");
        $mimallUser= M("mimall_user");
        $miyouquan = M('miyouquan');
        $media_tab = M("ind_media_info");
        Session::switchCustomer($cid);
        $weixinuser = M("user_weixin_info");
        $TemplateModel = M("template_messages");
        $twhere['status']=array("eq","recommended");
        $templatemsg = $TemplateModel->where($twhere)->find();
        $templateId = $templatemsg['templateId'];
        $quanUserInfo = $quanuser->alias("a")
            ->join("wx_quan_user b on a.refereeUid=b.uid and a.qid =b.qid")
            ->field("a.nickName,a.refereeUid,b.refereeUid as parRefereeUid")
            ->where("a.qid = $qid and a.uid = $uid")
            ->find();
        $quanInfo = $miyouquan->where("id=$qid")->find();
        $userInfo = $mimallUser->alias("a")
            ->join("wx_".$cid."_user_weixin_info b on a.openid=b.openid")
            ->where("a.openid='$userName'")
            ->field("a.fromModule,b.nickname")
            ->find();
        if(!$userInfo['nickname']||$userInfo['fromModule']<>'qrcode'){
            return;
        }
        /*$tempurl = C("SERVER_HOST") . "call.html?customerId=" . $cid .
            "&module=community&method=index&params=%7B%22qid%22:$qid%7D#/myfans";*/
        $http = WeixinApi::getDomainName();
        $tempurl =$http['RESOURCEURL'] . "spa/index.html#/quan/myFrends?customerId=".$cid."&param={'qId':".$qid."}";


        $mimallWhere['qId']=array("eq",$qid);
        $mimallWhere['cId']=array("eq",$cid);

        $mimallWhere['uId']=array("eq",$uid);
        $toUserInfo = $mimallUser->where($mimallWhere)->field("openid")->find();
        $data['first'] = array('value'=> '您推荐的好友'.$userInfo["nickname"].'关注成功','color'=>"#743A3A");
        $data['keyword1'] = array('value'=> $quanUserInfo["nickName"],'color'=>'#173177');
        $data['keyword2'] = array('value'=> $userInfo["nickname"],'color'=>'#173177');
        $data['remark'] = array('value'=> '点击查看详情',"color"=>'#008000');
        $toUser = $toUserInfo['openid'];
        $url = urlencode($tempurl);
        $topcolor = "#FF0000";
        WeixinApi::sendTpl($toUser, $templateId, $url,$topcolor,$data);

        if($quanUserInfo['refereeUid']&&$quanInfo['refereeAward']>0){
            $mimallWhere['uId']=array("eq",$quanUserInfo['refereeUid']);
            $toUserInfo = $mimallUser->where($mimallWhere)->field("openid")->find();
            $data['first'] = array('value'=> '您的好友'.$quanUserInfo["nickName"].'推荐的好友'.$userInfo["nickname"].'关注成功','color'=>"#743A3A");
            $data['keyword1'] = array('value'=> $quanUserInfo["nickName"],'color'=>'#173177');
            $data['keyword2'] = array('value'=> $userInfo["nickname"],'color'=>'#173177');
            $data['remark'] = array('value'=> '点击查看详情',"color"=>'#008000');
            $toUser = $toUserInfo['openid'];

            $url = urlencode($tempurl);
            $topcolor = "#FF0000";
            WeixinApi::sendTpl($toUser, $templateId, $url,$topcolor,$data);
        }

        if($quanUserInfo['parRefereeUid']&&$quanInfo['parentRefereeAward']>0){
            $mimallWhere['uId']=array("eq",$quanUserInfo['parRefereeUid']);
            $toUserInfo = $mimallUser->where($mimallWhere)->field("openid")->find();
            //$data['first'] = array('value'=> '喜讯！'.$userInfo["nickname"].'通过您的密友'.$quanUserInfo["nickName"].'的推荐，成为您的好友。','color'=>"#743A3A");
            $data['first'] = array('value'=> '您的好友'.$quanUserInfo["nickName"].'推荐的好友'.$userInfo["nickname"].'关注成功','color'=>"#743A3A");
            $data['keyword1'] = array('value'=> $quanUserInfo["nickName"],'color'=>'#173177');
            $data['keyword2'] = array('value'=> $userInfo["nickname"],'color'=>'#173177');
            $data['remark'] = array('value'=> '点击查看详情',"color"=>'#008000');
            $toUser = $toUserInfo['openid'];
            $url = urlencode($tempurl);
            $topcolor = "#FF0000";
            WeixinApi::sendTpl($toUser, $templateId, $url,$topcolor,$data);
        }
    }
    public static function promotionCode($param){
        $id = $param->id;
        $userName = $param->message->fromUserName;
        $result = WeixinApi::getUserInfo($userName);
        $tableModel=M("");
        $userInfo = $tableModel->table("wx_module_quanuser_vendor")->where("id = ".$id)->find();
        $weixinResult=$tableModel->table("wx_".$userInfo["cId"]."_user_weixin_info")->where("openid='".$userName."'")->find();
        $materialInfo = $tableModel->table("wx_".$userInfo["cId"]."_module_mall_store")->alias("a")
            ->join("wx_".$userInfo["cId"]."_material b on a.promotionReplyId =b.id")
            ->field("b.xml")
            ->find();
        $miUser=$tableModel->table("wx_mimall_user")->where("openid='".$userName."'")->find();
        if(!$miUser || count($miUser) < 1){
            $addData=array(
                "openid"=>$userName,
                "qId"=>$userInfo["qId"],
                "miUid"=>$userInfo["miUId"],
                "createTime"=>date('Y-m-d H:i:s'),
                "cId"=>$userInfo["cId"],
                "fromModule"=>"qrcode",
                "fromModuleId"=>$id
            );
            $tableModel->table("wx_mimall_user")->add($addData);
            self::newFansMessage($userInfo["qId"],$userInfo["miUId"],$userName,$userInfo["cId"]);
        }
        if(!$weixinResult||count($weixinResult)<1){
            $data["openid"]=$userName;
            $data["subscribe"]=$result->subscribe;
            $data["nickname"]= $result->nickname;
            $data["sex"] = $result->sex;
            $data["language"] = $result->language;
            $data["city"] = $result->city;
            $data["province"] = $result->province;
            $data["country"] = $result->country;
            $data["headimgurl"] = $result->headimgurl;
            $data["subscribe_time"] = date("Y-m-d H:i:s");
            $data["unionid"] = $result->unionid;
            $tableModel->table("wx_".$userInfo["cId"]."_user_weixin_info")->add($data);
        }else{
            $where['openid'] = $userName;
            $data["subscribe"]=$result->subscribe;
            $data["nickname"]= $result->nickname;
            $data["sex"] = $result->sex;
            $data["language"] = $result->language;
            $data["city"] = $result->city;
            $data["province"] = $result->province;
            $data["country"] = $result->country;
            $data["headimgurl"] = $result->headimgurl;
            $data["subscribe_time"] = date("Y-m-d H:i:s");
            $data["unionid"] = $result->unionid;
            $tableModel->table("wx_".$userInfo["cId"]."_user_weixin_info")->where($where)->save($data);
        }
        $xml = (string)$materialInfo["xml"];
        $xml = str_replace("{{nickname}}",$result->nickname,$xml);
        $xml = simplexml_load_string($xml,'SimpleXMLElement', LIBXML_NOCDATA);
        $item = $xml->Articles->item;
        $articles=array();
        foreach($item as $key=>$value){
            $article=new stdClass();
            $article->title = urlencode((string)$value->title);
            $article->url = urlencode((string)$value->url);
            $article->picurl = urlencode((string)$value->picUrl);
            $article->description = urlencode((string)$value->description);
            array_push($articles, $article);
        }
        $toUser = $userName;
        WeixinApi::sendServiceMsg($toUser, 'news','',$articles);
        $customerUserInfo = $tableModel->table("wx_customer")->where('id='.$userInfo["cId"])->find();
        if($customerUserInfo['isAutoGroup']) {
            if (!$userInfo["qId"]) {
                return;
            }
            $quanInfo = $tableModel->table("wx_miyouquan")->where("id=" . $userInfo["qId"])->find();
            $condition['group_name'] = array('eq', $quanInfo['name']);
            $groupResult = $tableModel->table("wx_" . $userInfo["cId"] . "_user_weixin_group")->where($condition)->find();
            if (!$groupResult) {
                $groupResult = WeixinApi::createUserTag($quanInfo['name']);
                $groupResult = json_decode($groupResult, true);
                if ($groupResult['errcode']) {
                    Log::write("创建分组失败   " . $groupResult['errmsg']);
                } else {
                    $groupId = $groupResult['tag']['id'];
                    $groupdata['group_id'] = $groupResult['tag']['id'];
                    $groupdata['group_name'] = $groupResult['tag']['name'];
                    $groupdata['count'] = 0;
                    $tableModel->table("wx_" . $userInfo["cId"] . "_user_weixin_group")->add($groupdata);
                }
            } else {
                $groupId = $groupResult['group_id'];
            }
            $groupIds = $tableModel->table("wx_" . $userInfo['cId'] . "_user")->where("userName='" . $userName . "'")->getField("groupId");
            $groupIds = explode(",", $groupIds);
            $flag = true;
            foreach($groupIds as $key=>$value){
                if($value==$groupId){
                    $flag = false;
                }else{
                    WeixinApi::deletedUsersTag(explode(',', $userName),$value);
                }
            }
            if($flag){
                WeixinApi::setUsersTag(explode(',', $userName),$groupId);
                $tableModel->table("wx_" . $userInfo['cId'] . "_user")->where("userName='$userName'")->setField("groupId", $groupId);
            }
        }
    }
    //分销商品列表
    public static function distributionProduct($qid){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
//        $vendorModel = M("quan_vendor");
        $miYouQuanModel = M("miyouquan");
        Session::switchCustomer($customerId);
        $vendorList = $miYouQuanModel->alias("a")
            ->join("inner join wx_mivendor b on a.vid=b.id")
            ->join("inner join wx_customer_user c on b.fromCustomerUserId=c.id")
            ->join("inner join wx_mimall d on c.customerId=d.fromCustomerId")
            ->field("d.logo,d.name,c.customerId as id")
            ->group("d.id")
            ->where("a.quanId=$qid and c.agent='vendor' and d.deleted=0")
            ->select();
        $result["vendorList"] = $vendorList;
        Output::instance()->object($result);
    }
    //通过条件筛选分销商品
    public static function getProductByCondition($cid,$tagId,$qid,$sort=0,$start=0,$limit=20,$name=''){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;

        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
//        $vendorModel = M("quan_vendor");
        $distribution = M("module_product_distribution");
        $quanModel = M("miyouquan");
        $productTagModel = M('module_product_tag_list');
        Session::switchCustomer($customerId);
        switch($sort){
            case 0:
                $order='b.updateTime desc';
                break;
            case 1:
                $order='b.createTime desc';
                break;
            case 2:
                $order='miAward desc';
                break;
            case 3:
                $order ='b.salesCount desc';
                break;
            case 4:
                $order = 'b.discountedPrice desc';
                break;
        }
        if($cid){
            $distributionList = $distribution->field("id,logo,name,tagId")->where("cId = $cid and deleted=0")->select();
            $result["distributionList"] = $distributionList;
            if(isset($tagId)&&$tagId){
                $distributionInfo = $distribution->where("id=$tagId")->find();
                $tagIds = $distributionInfo["tagId"];
            }else{
                $tagIds = array();
                foreach($distributionList as $key=>$value){
                    $tagId = explode(",",$value["tagId"]);
                    $tagIds = array_merge($tagIds,$tagId);

                }
                $tagIds=array_unique($tagIds);
                $tagIds =  implode(',', $tagIds);
            }
        }else{
            $vendorList = $quanModel->alias("a")
                ->join("inner join wx_mivendor b on a.vid=b.id")
                ->join("inner join wx_customer_user c on b.fromCustomerUserId=c.id")
                ->join("inner join wx_module_product_distribution d on d.cId=c.customerId")
                ->field("d.tagId")
                ->where("a.quanId=$qid and c.agent='vendor' and d.deleted=0")
                ->select();
            $tagIds = array();
            foreach($vendorList as $key=>$value){
                $tagId = explode(",",$value["tagId"]);
                $tagIds = array_merge($tagIds,$tagId);

            }
            $tagIds=array_unique($tagIds);
            $tagIds =  implode(',', $tagIds);
        }
        if($tagIds){
            $condition["d.module"] = array("eq","product");
            $condition["b.deleted"]=array("eq",0);
            $condition["b.isRemoved"] = array("eq",0);
//            $condition['f.deleted']=array("eq",0);
            $condition["e.id"]=array("eq",$qid);
            $condition["a.tagId"]=array("in",$tagIds);
            $condition['b.name']=array("like","%$name%");
            $productList = $quanModel->alias("e")
//                ->join("inner join wx_quan_vendor f on e.id = f.quanId")
                ->join("inner join wx_mivendor c on e.vid=c.id")
                ->join("inner join wx_module_product_tag_list a on a.tagId in ($tagIds)")
                ->join("inner join wx_module_product b on b.vId=c.id and b.id = a.pid")
                ->join("inner join wx_mishare d on d.moduleId=b.id")
                ->join("wx_module_product_specification spe on b.id=spe.pid")
                ->field("c.logo as vLogo,c.name as vName,b.*,ROUND((b.saleCut*e.miAward),2) as miAward,d.id as sId,
                max(spe.miPrice) as maxMiPrice,min(spe.miPrice) as minMiPrice,
                ROUND((min(spe.saleCut)*e.miAward),2) as minMiAward,ROUND((max(spe.saleCut)*e.miAward),2) as maxMiAward,
                min(spe.discountedPrice) as minDisPrice,max(spe.discountedPrice) as maxDisPrice,min(spe.fixedPrice) as minFixedPrice,
                max(spe.fixedPrice) as maxFixedPrice")
                ->where($condition)
                ->where("d.deleted=0 or d.deleted is NULL")
                ->group("b.id")
                ->limit($start,$limit)
                ->order($order)
                ->select();
            foreach($productList as $key=>$value){
                if($value["picUrl1"]){
                    $productList[$key]["picUrl1"] = json_decode($value["picUrl1"],true);
                }
            }
            $result["productList"] = $productList;
        }
        Output::instance()->object($result);
    }
    //商品生成二维码

    public static function getProductCode($module, $moduleId){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        $uId = Session::$user['userId'];
        Session::switchCustomer(0);
        $userProduct = M("module_quanuser_product");
        $productModel = M("module_product");
        $micontentModel = M("micontent");
        Session::switchCustomer($customerId);
        $codeResult = $userProduct->where(['moduleId' => $moduleId, 'module' => $module, 'cid' =>$customerId, 'uid' => $uId])->find();
        if($module == 'product'){
            $productInfo = $productModel->alias("a")
                ->join("inner join wx_mishare b on a.id=b.moduleId")
                ->join("wx_module_product_specification spe on a.id=spe.pid")
                ->field("a.*,b.id as sid,MIN(spe.discountedPrice) as minDisPrice,MAX(spe.discountedPrice) as maxDisPrice,
				MIN(spe.miPrice) as minMiPrice,MAX(spe.miPrice) as maxMiPrice,MAX(spe.fixedPrice) as maxFixedPrice,MIN(spe.fixedPrice) as minFixedPrice,MAX(spe.seckillPrice) as maxSeckillPrice,MIN(spe.seckillPrice) as minSeckillPrice")
                ->where("a.id=$moduleId and b.module='product'")->find();
            if($productInfo["freeBuy"]&&$productInfo["freeBuyMoney"]){
                $price = explode(",",$productInfo["freeBuyMoney"]);
                $price = "￥".$price[0];
            }else if($productInfo["teambuy"]){
                $price = "￥".$productInfo["teamPrice"];
            }else if($productInfo["playType"]==3){
                $price = "￥".$productInfo["perMoney"];
            }else if($productInfo['playType']==4&&$productInfo['supportSpecification']&&$productInfo['minSeckillPrice']!=$productInfo['maxSeckillPrice']){
                $price = "￥" . $productInfo["minSeckillPrice"] . "~" . $productInfo["maxSeckillPrice"];
            }else if($productInfo['playType']==4){
                $price = "￥" . $productInfo["seckillPrice"];
            }else if($productInfo['playType']==5&&$productInfo['supportSpecification']&&$productInfo['minMiPrice']!=$productInfo['maxMiPrice']) {
                $price = "￥" . $productInfo["minMiPrice"] . "~" . $productInfo["maxMiPrice"];
            }else if($productInfo['playType']==5&&$productInfo['supportSpecification']) {
                $price = "￥" . $productInfo["minMiPrice"];
            }else if($productInfo['playType']==5){
                $price = "￥".$productInfo["miPrice"];
            }else if($productInfo["discountedPrice"]&&$productInfo['supportSpecification']&&$productInfo['minDisPrice']!=$productInfo['maxDisPrice']) {
                $price = "￥" . $productInfo["minDisPrice"] . "~" . $productInfo["maxDisPrice"];
            }else if($productInfo["discountedPrice"]&&$productInfo['supportSpecification']) {
                $price = "￥" . $productInfo["minDisPrice"];
            }else if($productInfo["discountedPrice"]){
                $price = "￥".$productInfo["discountedPrice"];
            }else if($productInfo['supportSpecification']&&$productInfo['minFixedPrice']!=$productInfo['maxFixedPrice']) {
                $price = "￥" . $productInfo["minFixedPrice"] . "~" . $productInfo["maxFixedPrice"];
            }else if($productInfo['supportSpecification']) {
                $price = "￥" . $productInfo["minFixedPrice"];
            }else{
                $price = "￥".$productInfo["fixedPrice"];
            }
            if($productInfo["picUrl1"]){
                $picUrl = json_decode($productInfo["picUrl1"],true);
                if($picUrl[1]){
                    $productInfo["picUrl"]=$picUrl[1]['picUrl'];
                }
            }
            $updateTime = strtotime($productInfo['updateTime']);
            $sid = strtotime($productInfo['sid']);
            $method = 'getProduct';
        }
        elseif ($module == 'micontent'){
            $micontentInfo = $micontentModel ->alias('a')->join("wx_mishare b on a.id=b.moduleId")->where(['a.id' => $moduleId,'b.module' => 'micontent'])->field('a.*,b.id as sid')->find();
            $updateTime = strtotime($micontentInfo['updateTime']);
            $sid = strtotime($micontentInfo['sid']);
            $method = 'getMiContentDetail';
        }

        $mallModel = M("");
        $mallInfo =$mallModel->table("wx_".$productInfo['fromCustomerId']."_module_mall_store")->find();

        $codeTime = strtotime($codeResult['createTime']);
        if(!$codeResult||$updateTime>$codeTime){
            if(!empty($codeResult)){
                $userProduct->where(['moduleId' => $moduleId, 'module' => $module, 'cid' =>$customerId, 'uid' => $uId])->delete();
            }
            $data=array(
                "moduleId"=>$moduleId,
                "module"=>$module,
                "uid"=>$uId,
                "sid"=>$sid,
                "pv"=>0,
                "cid"=>$customerId,
                "createTime"=>date("Y-m-d H:i:s")
            );
            $id = $userProduct->add($data);
            $_GET["customerId"]=$customerId;
            $p=new StdClass();
            $p->id=$moduleId;
            $p->uid=$uId;
            $p->scanId=$id;
            $p->isDefault=1;
            $p->sid=$sid;
            $p=urlencode(json_encode($p));
            $url = WeixinApi::getDomainName();
            $location=$url['SERVER_HOST']. 'call.html?customerId='.$customerId.'&module='.$module.'&method='.$method.'&params='.$p;
            $location = urlencode($location);
            $shortUrl = WeixinApi::long2short($location);
            $shortUrl = json_decode($shortUrl);
            if(!$shortUrl->errcode){
                $location = $shortUrl->short_url;
            }else{
                Output::instance()->resultCode(1,"链接转换失败");
                return;
            }
            $fname="productQRcode.png";
            $fileName=LOCAL_PIC_PATH . "$fname";
            PhpQRcode::png($location, $fileName, 'L', 9,4);
            $qrImg = $fileName;
            $fileName = time().$uId;
            if($module == 'product'){
                $out = self::createProductImage($fileName,$qrImg,$productInfo["picUrl"],$productInfo["name"],$price,$mallInfo['name'],$productInfo['recommend'],$productInfo['fixedPrice']);
            }else{
                $out = self::createMiContentImage($fileName,$qrImg,$micontentInfo["bigPicUrl"],$micontentInfo["title"],$micontentInfo['recomment'],$mallInfo['name']);
            }
            if($out && !$out->code){
                @unlink ($qrImg);
                $updateData["qrImg"]=$out->path;
                $qrImg = $out->path;
                $userProduct->where("id=$id")->save($updateData);
            } else {
                Output::instance()->resultCode(1,$out->msg);
                return;
            }
        }else{
            $qrImg = $codeResult["qrImg"];
        }
        $result['results'][0]["qrImgUrl"] = $qrImg;
        Output::instance()->module('community','poster')->object($result);
        exit;
    }
    public function createProductImage($fileName,$qrImg,$proPicUrl,$proName,$price,$mallName,$proRecommend,$fixedPrice){
        $fname="proCode_$fileName.png";
        $fileName=LOCAL_PIC_PATH . "/$fname";
        $img = imagecreatetruecolor(640,1004);
        $color = imagecolorallocate($img,255,255,255);   //分配一个灰色
        imagefill($img,0,0,$color);
        if(!$img) {
            $out1 = new stdClass();
            $out1->code=1;
            $out1->msg="背景图片获取错误，请重试";
            return $out1;
        }
        $imgWidth=imagesx($img);
        $fp = fopen($qrImg, 'rb');
        $qrImg = fread($fp, filesize($qrImg)); //二进制数据
        fclose($fp);
        $qrImg=imagecreatefromstring($qrImg);
        if(!$qrImg) {
            $out1=new StdClass();
            $out1->code=1;
            $out1->msg="二维码生成错误，请重试";
            return $out1;
        }
        $qrImgWidth=imagesx($qrImg);
        $qrImgHeight=imagesy($qrImg);
        imagecopyresampled($img,$qrImg,0,780,0,0,180,180,$qrImgWidth,$qrImgHeight);
        $headImg=self::curls($proPicUrl);
        $headImg=imagecreatefromstring($headImg);

        $headImgWidth=imagesx($headImg);
        $headImgHeight=imagesy($headImg);
        imagecopyresampled($img,$headImg,0,200,0,0,640,580,$headImgWidth,$headImgHeight);

        $fontcolor=imagecolorallocate($img,255,83,139);
        $font=__DIR__."/FZLTHJW.TTF";
        $fontsize=30;
        $fontsize1=30;
        imagettftext($img,$fontsize,0,200,830,$fontcolor,$font,$price);
        $width = $imgWidth-40;
        $fontcolor1=imagecolorallocate($img,15,15,15);
        $text = self::autowrap($fontsize1, 0,$font, $proName, $width); // 自动换行处理
        imagettftext($img,$fontsize1,0,30,60,$fontcolor1,$font,$text);

        $fontsize1=18;
        $width = $imgWidth-40;
        $fontcolor1=imagecolorallocate($img,51,51,51);
        $desciption = "(长按立即购买)";
        $text = self::autowrap($fontsize1, 0,$font, $desciption, $width); // 自动换行处理
        imagettftext($img,$fontsize1,0,15,980,$fontcolor1,$font,$text);

        $fontsize2=18;
        $fontcolor1=imagecolorallocate($img,128,128,128);
        $text = $proRecommend;
        $text = self::autowrap($fontsize1, 0,$font, $text, 610); // 自动换行处理

        imagettftext($img,$fontsize2,0,30,150,$fontcolor1,$font,$text);
        if(!empty($fixedPrice)){
                $text = "￥".$fixedPrice;
                imagettftext($img,$fontsize2,0,350,830,$fontcolor1,$font,$text);
                $text = "______";
                imagettftext($img,$fontsize2,0,350,817,$fontcolor1,$font,$text);
        }
        imagejpeg($img,$fileName);
        imagedestroy($img);
        imagedestroy($headImg);
        imagedestroy($line);
        //开始上传
        if( $qrImg) {
            if(file_exists($fileName)){
                $out=R("Upload/uploadLocalFileToOss",array($fname,$fileName));
                if(!$out->code){
                    return $out;
                }
            }
        } else {
            $out=new StdClass();
            $out->code=1;
            return $out;
        }
    }

    public function createMiContentImage($fileName,$qrImg,$miConPicUrl,$miConName,$miConRecomment,$mallName){
        $fname="proCode_$fileName.png";
        $fileName=LOCAL_PIC_PATH . "/$fname";
        $img = imagecreatetruecolor(640,1004);
        $color = imagecolorallocate($img,255,255,255);   //分配一个灰色
        imagefill($img,0,0,$color);
        if(!$img) {
            $out1 = new stdClass();
            $out1->code=1;
            $out1->msg="背景图片获取错误，请重试";
            return $out1;
        }

        $headImg=self::curls($miConPicUrl);
        $headImg=imagecreatefromstring($headImg);
        $headImgWidth=imagesx($headImg);
        $headImgHeight=imagesy($headImg);
        imagecopyresampled($img,$headImg,0,0,0,0,640,300,$headImgWidth,$headImgHeight);

        $picUrl = DOWNPICURL;
        $headImg=self::curls($picUrl);
        $headImg=imagecreatefromstring($headImg);
        $qrImgWidth=imagesx($headImg);
        $qrImgHeight=imagesy($headImg);
        imagecopyresampled($img,$headImg,19,200,0,0,605,800,$qrImgWidth,$qrImgHeight);

        $imgWidth=imagesx($img);
        $imgHeight=imagesy($img);
        $fp = fopen($qrImg, 'rb');
        $qrImg = fread($fp, filesize($qrImg)); //二进制数据
        fclose($fp);
        $qrImg=imagecreatefromstring($qrImg);
        if(!$qrImg) {
            $out1=new StdClass();
            $out1->code=1;
            $out1->msg="二维码生成错误，请重试";
            return $out1;
        }
        $qrImgWidth=imagesx($qrImg);
        $qrImgHeight=imagesy($qrImg);
        imagecopyresampled($img,$qrImg,330,700,0,0,210,210,$qrImgWidth,$qrImgHeight);

        $font=__DIR__."/FZLTHJW.TTF";
        $fontsize1=30;
        $fontcolor1=imagecolorallocate($img,15,15,15);
        $text = self::autowrap($fontsize1, 0,$font, $miConName, 490); // 文章标题自动换行处理
        imagettftext($img,$fontsize1,0,90,350,$fontcolor1,$font,$text);

        $fontsize1=20;
        $width = $imgWidth-40;
        $fontcolor1=imagecolorallocate($img,51,51,51);
        $desciption = "(长按立即购买)";
        $text = self::autowrap($fontsize1, 0,$font, $desciption, $width); // 自动换行处理
        imagettftext($img,$fontsize1,0,350,920,$fontcolor1,$font,$text);

        $fontsize2=18;
        $fontcolor1=imagecolorallocate($img,128,128,128);
        $text = $miConRecomment;
	$text = self::autowrap($fontsize2, 0,$font, $text, 480); // 推荐语自动换行处理
        imagettftext($img,$fontsize2,0,90,460,$fontcolor1,$font,$text);

        imagejpeg($img,$fileName);
        imagedestroy($img);
        imagedestroy($headImg);
        imagedestroy($line);
        //开始上传
        if( $qrImg) {
            if(file_exists($fileName)){
                $out=R("Upload/uploadLocalFileToOss",array($fname,$fileName));
                if(!$out->code){
                    return $out;
                }
            }
        } else {
            $out=new StdClass();
            $out->code=1;
            return $out;
        }
    }
    //推荐人首页
    public static function refereeInfo($qid,$start=0,$limit=20){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        $uId = Session::$user['userId'];
        Session::switchCustomer(0);
        $quanUserModel = M("quan_user");
        $quanModel = M("miyouquan");
        Session::switchCustomer($customerId);
        $quanInfo = $quanModel->where("id = $qid")->find();
        $refereeList = $quanUserModel->alias("a")
            ->join("inner join wx_quan_user b on a.uid = b.uid and b.qid = $qid")
            ->join("inner join wx_".$customerId."_user c on b.uid = c.id")
            ->field("b.nickName,b.headImgUrl,c.fullName")
            ->group("b.id")
            ->where("a.qid=$qid and a.refereeUid = $uId and b.status=1 and b.deleted=0")
            ->limit($start,$limit)
            ->select();
        $result["refereeList"] = $refereeList;
        $result["quanInfo"] = $quanInfo;
        Output::instance()->object($result);
    }
    public static function setRefereeUrl($qid,$uId,$refereeUrl){
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $mishareModel = M("mishare");
        Session::switchCustomer($customerId);
        $params = new stdClass();
        $Guid = new Guid();
        $params->fromGuid=$Guid->toString();
        $params->qId = $qid;
        $params->miUId=$uId;
        $url = self::getTpl($refereeUrl);
        $param = $url["param"];
        $id = $param->id;
        $module = strpos($url["url"],"module");
        $method = strpos($url["url"],"method");
        if($module||$method){
            $start=$module+strlen("module=");
            $length = strpos($url["url"],"&",$module)-$start;
            $module = substr($url["url"],$start,$length);
            $start=$method+strlen("method=");
            $length = strpos($url["url"],"&",$method)-$start;
            $method = substr($url["url"],$start,$length);
        }else{
            return;
        }
        switch($module){
            case "micontent":
                $shareInfo = $mishareModel->alias("a")
                    ->join("inner join wx_micontent b on a.moduleId=b.id")
                    ->where("a.module='micontent' and a.moduleId = $id and (a.deleted =0 or a.deleted is null) and b.deleted =0")
                    ->field("a.id,b.fromCustomerId")
                    ->find();
                $params->contentId = $id;
                break;
            case "product":
                $shareInfo = $mishareModel->alias("a")
                    ->join("inner join wx_module_product b on a.moduleId=b.id")
                    ->where("a.module='product' and a.moduleId = $id and (a.deleted =0 or a.deleted is null) and b.isRemoved=0 and b.deleted=0")
                    ->field("a.id,b.fromCustomerId")
                    ->find();
                $params->pid = $id;
                break;
        }
        $params->module = $module;
        $params->method = $method;
        $params->id = $shareInfo["id"];
        $params->customerId = $shareInfo["fromCustomerId"];
        $refereeUrl = C("SERVER_HOST")."call.html?customerId=".C("PLANT_CUSTOMERID")."&module=quan&scope=1&method=goToCustomer&params=".urlencode(json_encode($params));
        return $refereeUrl;
    }
    //获得分享人联系配置
    public static function getContactInfo($qid,$uid){
        $customerId = Session::$user['customerId'];
        if(!$uid){
            return false;
        }
        Session::switchCustomer(0);
        $quanUser = M("quan_user");
        Session::switchCustomer($customerId);
        $where['a.qid']=array("eq",$qid);
        $where['a.uid']=array("eq",$uid);
        $where['a.deleted']=array("eq",0);
        $where['a.status']=array("eq",1);
        $quanInfo = $quanUser->alias("a")
            ->join("inner join wx_miyouquan b on a.qid=b.id")
            ->join("wx_quan_user c on a.saleSource=c.uid and a.qid=c.qid and c.deleted=0 and c.status=1")
            ->join("wx_".$customerId."_user d on a.uid=d.id")
            ->join("wx_".$customerId."_user e on a.saleSource=e.id")
            ->where($where)
            ->field("a.configJson,b.config,b.contactEnable,b.contactInherit,a.isSaleSource,a.saleSource,
            c.configJson as saleSourceJson,c.nickname as saleSourceNickname,
            c.headImgUrl as saleSourceHeadImgUrl,a.nickName,
            a.headImgUrl,d.fullName,d.phone,d.qrcodeUrl as qrcode,
            e.fullName as saleSourceFullName,e.phone as saleSourcePhone,
            e.qrcodeUrl as saleSourceQrcode")
            ->find();
        //判断圈是否设置好友联系方式，不设置则返回
        if(!$quanInfo['contactEnable']){
            return false;
        }
        //$currentUser = $quanUser->where(['uid'=>$currentUid,'deleted'=>0,'status'=>1,'qid'=>$qid])->find();
        //contactEnable=1仅销售源开启,2普通好友可开启
        //contactInherit=0不继承,1继承
        //销售源开启。继承：关闭。 仅销售源可以展示自己的详情信息，普通好友那里没有信息展示.裸链接(圈子里面)普通好友不展示
        if($quanInfo['contactEnable']==1&&$quanInfo['contactInherit']==0&&!$quanInfo['isSaleSource']){
            return false;
        }
        //销售源开启。继承：开启。销售源可以展示自己的详情信息，普通好友继承销售源信息
        if($quanInfo['contactEnable']==1&&$quanInfo['contactInherit']){
            if(!$quanInfo['isSaleSource'] && !$quanInfo['saleSource']){
                return false;
            }
            //$quanInfo['configJson'] =  $quanInfo['saleSourceJson'];
            $quanInfo['headImgUrl'] =  $quanInfo['saleSourceHeadImgUrl'];
            $quanInfo['fullName'] =  $quanInfo['saleSourceFullName'];
            $quanInfo['nickName'] =  $quanInfo['saleSourceNickname'];
            $quanInfo['phone'] =  $quanInfo['saleSourcePhone'];
            $quanInfo['qrcode'] =  $quanInfo['saleSourceQrcode'];

        }
        //普通开通。继承：关闭。销售源可展示自己的详情信息，普通好友那里展示自己信息。
        //普通开通。继承：开启。销售源可展示自己的详情信息，普通好友那里展示销售源信息。
        if($quanInfo['contactEnable']==2&&$quanInfo['contactInherit']){
            //$quanInfo['configJson'] =  $quanInfo['saleSourceJson'];
            $quanInfo['headImgUrl'] =  $quanInfo['saleSourceHeadImgUrl'];
            $quanInfo['fullName'] =  $quanInfo['saleSourceFullName'];
            $quanInfo['nickName'] =  $quanInfo['saleSourceNickname'];
            $quanInfo['phone'] =  $quanInfo['saleSourcePhone'];
            $quanInfo['qrcode'] =  $quanInfo['saleSourceQrcode'];

        }

        //原来获取手机号和二维码图片的地方，已废弃
        // if($quanInfo&&$quanInfo['configJson']){
        //     $json = json_decode($quanInfo['configJson'],true);
        //     $quanInfo['phone'] =  $json['phone'];
        //     $quanInfo['qrcode'] =  $json['qrcode'];
        // }
        if($quanInfo&&$quanInfo['config']){
            $json = json_decode($quanInfo['config'],true);
            $reveal = $json['reveal'];
            $quanInfo['phoneTitle'] = $reveal['phoneTitle'];
            $quanInfo['qrcodeTitle'] = $reveal['qrcodeTitle'];
            $quanInfo['contactTitle'] = $reveal['contactTitle'];
            $quanInfo['contactTel'] = $reveal['contactTel'];
        }
        unset($quanInfo['config']);
        unset($quanInfo['configJson']);
        unset($quanInfo['saleSourceJson']);
        return $quanInfo;
    }
    public static function quanTeam($teamId){
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $quanTeam = M("quan_team");
        $quanUser = M("quan_user");
        Session::switchCustomer($customerId);
        $teamWhere["b.deleted"]=array("eq",0);
        $teamWhere["b.status"]=array("eq",1);
        $prevTime=date('Y-m-1 0:0:0');
        $teamWhere["a.id"]=array("eq",$teamId);
        $result = $quanTeam->alias("a")
            ->join("inner join wx_quan_user b on a.id=b.teamId")
            ->join("left join wx_module_product_order c on b.qid=c.qId and c.miUid=b.uid and c.completionTime>'$prevTime' and c.status='ok'")
            ->join("wx_quan_team_month_statistics d on a.id = d.teamId and d.createTime>='$prevTime'")
            ->where($teamWhere)
            ->field("a.id,a.teamLeader,count(c.id) as orderCount,sum(c.price) as sales,a.totalPerson,d.sales as preMonthSales,d.person,d.totalPerson as preMonthTotalPerson,
            d.order as preMonthOrder,d.avgSales as preMonthAvgSales")
            ->group("a.id")
            ->find();
        $teamLeaderInfo = $quanUser->where("teamId=$teamId and uid = ".$result['teamLeader'])->field("nickName,headImgUrl")->find();
        $result['nickName'] = $teamLeaderInfo['nickName'];
        $result['headImgUrl'] = $teamLeaderInfo['headImgUrl'];
        $result['persons'] = $quanUser->where("joinTeamTime>'$prevTime' and teamId=$teamId")->count();
        if($result){
            !$result['sales']?$result['sales']=0:"";
            $result['avgSales']=round($result['sales']/$result['totalPerson'],2);
            $result['preMonthAddPerson'] = round($result['person']/$result['preMonthTotalPerson'],2)*100;
            $result['addPerson'] = round($result['persons']/($result['totalPerson']-$result['persons']),2)*100;
            $result['preMonthTotalPerson'] = $result['preMonthTotalPerson']+$result['person'];
        }
        $result['uid']=Session::$user['userId'];
        Output::instance()->object($result);
    }
    public static function teamUser($id,$uid,$start=0,$limit=10){
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $quanUser = M("quan_user");
        $quanTeam = M("quan_team");
        Session::switchCustomer($customerId);
        $json = $quanTeam->alias("a")
            ->join("inner join wx_miyouquan b on a.quanId=b.id")
            ->where("a.id=$id")
            ->getField("b.json");
        $json = json_decode($json,true);
        $probation = $json['salcesReward']['probation'];
        $prevTime=date('Y-m-1 0:0:0');
        $where["a.status"]=array("eq",1);
        $where["a.deleted"]=array("eq",0);
        $where["a.teamId"]=array("eq",$id);
        $where["a.uid"]=array("neq",$uid);
        $result = $quanUser->alias("a")
            ->join("wx_module_product_order b on a.qid = b.qId and a.uid = b.miUid and b.status = 'ok' and b.completionTime>'$prevTime'")
            ->join("wx_quan_user_month_statistics c on a.qid = c.quanId and a.uid=c.uId and c.createTime>='$prevTime'")
            ->where($where)
            ->limit($start,$limit)
            ->field("a.id,a.uid,a.joinTeamTime,a.nickName,a.headImgUrl,sum(b.price) as salces,count(b.id) as orderCount,c.sales,c.order")
            ->group("a.id")
            ->select();
        if($result){
            foreach($result as $key=>$value){
                if(strtotime($value['joinTeamTime']." + $probation day")<time()){
                    $result[$key]['canDel']=1;
                }else{
                    $result[$key]['canDel']=0;
                }
                $result[$key]['joinTeamTime']=date("Y-m-d",strtotime($value['joinTeamTime']));
            }
        }
        Output::instance()->object($result);
    }
    //从团队中删除
    public static function deletedTeamUser($id){
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $quanUser = M("quan_user");
        $quanTeam = M("quan_team");
        $orderModel = M("module_product_order");
        Session::switchCustomer($customerId);
        $userInfo = $quanUser->alias("a")
            ->join("inner join wx_quan_team b on a.teamId=b.id")
            ->where("a.id=$id")->field("a.qid,a.uid,a.joinTeamTime,a.teamId,b.totalPerson,b.totalSales,b.totalOrder")->find();
        $quanResult = $quanUser->where("id=$id")->setfield(["teamId"=>NULL,"joinTeamTime"=>NULL]);
        $nowTime = date("Y-m-1 0:0:0");
        $qid = $userInfo['qid'];$uid = $userInfo['uid'];
        $orderInfo = $orderModel->where("qId=$qid and miUid=$uid and status='ok' and completionTime>'$nowTime'")->field("sum(price) as sales,count(id) as orders")->find();
        $teamData['totalPerson']=$userInfo['totalPerson']-1;
        $teamData['totalSales']=$userInfo['totalSales']-$orderInfo['sales'];
        $teamData['totalOrder']=$userInfo['totalOrder']-$orderInfo['orders'];
        $quanTeam->where("id=".$userInfo['teamId'])->save($teamData);
        if($quanResult!==false){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }

    }
    //邀请加入团队
    public function inviteJoinTeam($id,$time){
        $customerId = Session::$user['customerId'];
        $uid = Session::$user['userId'];
        Session::switchCustomer(0);
        $quanTeam = M("quan_team");
        $quanUser = M("quan_user");
        Session::switchCustomer($customerId);
        $qid = $quanTeam->where("id=$id")->getField("quanId");
        $userInfo = $quanUser->where("qid=$qid and uid=$uid")->find();
        $result = $quanTeam->alias("a")
            ->join("inner join wx_quan_user b on a.teamLeader=b.uid and a.quanId=b.qid")
            ->where("a.id=$id")
            ->field("b.nickname,b.headimgurl")->find();
        $result['time']=$time;
        $result['userInfo']=$userInfo;
        Output::instance()->module("community","joinTeam")->object($result);
    }
    public function joinTeam($id){
        $customerId = Session::$user['customerId'];
        $uid = Session::$user['userId'];
        Session::switchCustomer(0);
        $quanTeam = M("quan_team");
        $quanUser = M("quan_user");
        $orderModel= M("module_product_order");
        Session::switchCustomer($customerId);
        $qid = $quanTeam->where("id=$id")->getField("quanId");
        $data['teamId']=$id;
        $data['joinTeamTime']=date("Y-m-d H:i:s");
        $quanUser->where("qid=$qid and uid=$uid")->save($data);
        $nowTime = date("Y-m-1 0:0:0");
        $orderInfo = $orderModel->where("qId=$qid and miUid=$uid and status='ok' and completionTime>'$nowTime'")->field("sum(price) as sales,count(id) as orders")->find();
        if(!$orderInfo['sales']){
            $orderInfo['sales']=0;
        }
        $sql = "UPDATE wx_quan_team SET totalPerson=totalPerson+1,totalSales=totalSales+".$orderInfo['sales'].",totalOrder=totalOrder+".$orderInfo['orders']." WHERE id=".$id;
        $quanTeam->query($sql);
        self::sendTeamMessages($qid,$uid);
        Output::instance()->resultCode();
    }
    public function sendTeamMessages($qid,$uid){
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $quanUser = M("quan_user");
        $miyouquan = M("miyouquan");
        $mimallUser = M("mimall_user");
        $mallInfo = $miyouquan->alias("a")
            ->join("inner join wx_mimall b on a.mallId=b.id")
            ->field("b.fromCustomerId")
            ->where("a.id=$qid")
            ->find();
        $mallCId = $mallInfo['fromCustomerId'];
        Session::switchCustomer($mallCId);
        $TemplateModel = M("template_messages");
        $twhere['status']=array("eq","makepartner");
        $templatemsg = $TemplateModel->where($twhere)->find();
        $userInfo = $quanUser->alias("a")
            ->join("wx_quan_team c on a.teamId=c.id")
            ->field("a.nickName,a.joinTeamTime,c.teamLeader")
            ->where("a.qid = $qid and a.uid = $uid")
            ->find();
        $templateId = $templatemsg['templateId'];
        $url = C("SERVER_HOST") . "call.html?customerId=" . $cid .
            "&module=community&method=index&params=%7B%22qid%22:$qid%7D#/team";
        $mimallWhere['qId']=array("eq",$qid);
        $mimallWhere['cId']=array("eq",$mallCId);
        if($userInfo['teamLeader']){
            $mimallWhere['uId']=array("eq",$userInfo['teamLeader']);
            $teamLeaderInfo = $mimallUser->where($mimallWhere)->field("openid")->find();
            $data['first'] = array('value'=> '给力！您的团队新增一名密友'.$userInfo['nickName'],'color'=>"#743A3A");
            $data['keyword1'] = array('value'=> $userInfo["nickName"],'color'=>'#173177');
            $data['keyword2'] = array('value'=> $userInfo["joinTeamTime"],'color'=>'#173177');
            $data['remark'] = array('value'=> '您的团队中又多了一位密友，点击进入【我的团队】瞧瞧吧。',"color"=>'#008000');
            $toUser = $teamLeaderInfo['openid'];
            $url = urlencode($url);
            $topcolor = "#FF0000";
            WeixinApi::sendTpl($toUser, $templateId, $url,$topcolor,$data,TRUE,$mallCId);
        }
    }
    public static function getFaceboxInfo($mark){
        $faceboxList = self::getFacebox();
        foreach($faceboxList as $face){
            if($face->mark==$mark){
                return $face;
            }
        }
        return null;
    }
    public static function getFacebox(){
        $facebox = array();
        $face = new stdClass();
        $face->id=0;
        $face->mark = '[微笑]';
        $face->url = 'mp/assets/imgs/facebox/0.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=1;
        $face->mark = '[撇嘴]';
        $face->url = 'mp/assets/imgs/facebox/1.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=2;
        $face->mark = '[色]';
        $face->url = 'mp/assets/imgs/facebox/2.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=3;
        $face->mark = '[发呆]';
        $face->url = 'mp/assets/imgs/facebox/3.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=4;
        $face->mark = '[得意]';
        $face->url = 'mp/assets/imgs/facebox/4.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=5;
        $face->mark = '[流泪]';
        $face->url = 'mp/assets/imgs/facebox/5.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=6;
        $face->mark = '[害羞]';
        $face->url = 'mp/assets/imgs/facebox/6.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=7;
        $face->mark = '[闭嘴]';
        $face->url = 'mp/assets/imgs/facebox/7.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=8;
        $face->mark = '[睡]';
        $face->url = 'mp/assets/imgs/facebox/8.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=9;
        $face->mark = '[大哭]';
        $face->url = 'mp/assets/imgs/facebox/9.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=10;
        $face->mark = '[尴尬]';
        $face->url = 'mp/assets/imgs/facebox/10.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=11;
        $face->mark = '[发怒]';
        $face->url = 'mp/assets/imgs/facebox/11.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=12;
        $face->mark = '[调皮]';
        $face->url = 'mp/assets/imgs/facebox/12.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=13;
        $face->mark = '[呲牙]';
        $face->url = 'mp/assets/imgs/facebox/13.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=14;
        $face->mark = '[惊讶]';
        $face->url = 'mp/assets/imgs/facebox/14.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=15;
        $face->mark = '[难过]';
        $face->url = 'mp/assets/imgs/facebox/15.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=16;
        $face->mark = '[酷]';
        $face->url = 'mp/assets/imgs/facebox/16.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=17;
        $face->mark = '[冷汗]';
        $face->url = 'mp/assets/imgs/facebox/17.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=18;
        $face->mark = '[抓狂]';
        $face->url = 'mp/assets/imgs/facebox/18.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=19;
        $face->mark = '[吐]';
        $face->url = 'mp/assets/imgs/facebox/19.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=20;
        $face->mark = '[偷笑]';
        $face->url = 'mp/assets/imgs/facebox/20.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=21;
        $face->mark = '[可爱]';
        $face->url = 'mp/assets/imgs/facebox/21.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=22;
        $face->mark = '[白眼]';
        $face->url = 'mp/assets/imgs/facebox/22.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=23;
        $face->mark = '[傲慢]';
        $face->url = 'mp/assets/imgs/facebox/23.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=24;
        $face->mark = '[饥饿]';
        $face->url = 'mp/assets/imgs/facebox/24.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=25;
        $face->mark = '[困]';
        $face->url = 'mp/assets/imgs/facebox/25.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=26;
        $face->mark = '[惊恐]';
        $face->url = 'mp/assets/imgs/facebox/26.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=27;
        $face->mark = '[流汗]';
        $face->url = 'mp/assets/imgs/facebox/27.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=28;
        $face->mark = '[憨笑]';
        $face->url = 'mp/assets/imgs/facebox/28.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=29;
        $face->mark = '[大兵]';
        $face->url = 'mp/assets/imgs/facebox/29.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=30;
        $face->mark = '[奋斗]';
        $face->url = 'mp/assets/imgs/facebox/30.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=31;
        $face->mark = '[咒骂]';
        $face->url = 'mp/assets/imgs/facebox/31.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=32;
        $face->mark = '[疑问]';
        $face->url = 'mp/assets/imgs/facebox/32.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=33;
        $face->mark = '[嘘]';
        $face->url = 'mp/assets/imgs/facebox/33.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=34;
        $face->mark = '[晕]';
        $face->url = 'mp/assets/imgs/facebox/34.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=35;
        $face->mark = '[折磨]';
        $face->url = 'mp/assets/imgs/facebox/35.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=36;
        $face->mark = '[衰]';
        $face->url = 'mp/assets/imgs/facebox/36.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=37;
        $face->mark = '[骷髅]';
        $face->url = 'mp/assets/imgs/facebox/37.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=38;
        $face->mark = '[敲打]';
        $face->url = 'mp/assets/imgs/facebox/38.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=39;
        $face->mark = '[再见]';
        $face->url = 'mp/assets/imgs/facebox/39.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=40;
        $face->mark = '[擦汗]';
        $face->url = 'mp/assets/imgs/facebox/40.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=41;
        $face->mark = '[抠鼻]';
        $face->url = 'mp/assets/imgs/facebox/41.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=42;
        $face->mark = '[鼓掌]';
        $face->url = 'mp/assets/imgs/facebox/42.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=43;
        $face->mark = '[糗大了]';
        $face->url = 'mp/assets/imgs/facebox/43.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=44;
        $face->mark = '[坏笑]';
        $face->url = 'mp/assets/imgs/facebox/44.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=45;
        $face->mark = '[左哼哼]';
        $face->url = 'mp/assets/imgs/facebox/45.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=46;
        $face->mark = '[右哼哼]';
        $face->url = 'mp/assets/imgs/facebox/46.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=47;
        $face->mark = '[哈欠]';
        $face->url = 'mp/assets/imgs/facebox/47.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=48;
        $face->mark = '[鄙视]';
        $face->url = 'mp/assets/imgs/facebox/48.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=49;
        $face->mark = '[委屈]';
        $face->url = 'mp/assets/imgs/facebox/49.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=50;
        $face->mark = '[快哭了]';
        $face->url = 'mp/assets/imgs/facebox/50.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=51;
        $face->mark = '[阴险]';
        $face->url = 'mp/assets/imgs/facebox/51.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=52;
        $face->mark = '[亲亲]';
        $face->url = 'mp/assets/imgs/facebox/52.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=53;
        $face->mark = '[吓]';
        $face->url = 'mp/assets/imgs/facebox/53.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=54;
        $face->mark = '[可怜]';
        $face->url = 'mp/assets/imgs/facebox/54.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=55;
        $face->mark = '[菜刀]';
        $face->url = 'mp/assets/imgs/facebox/55.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=56;
        $face->mark = '[西瓜]';
        $face->url = 'mp/assets/imgs/facebox/56.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=57;
        $face->mark = '[啤酒]';
        $face->url = 'mp/assets/imgs/facebox/57.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=58;
        $face->mark = '[篮球]';
        $face->url = 'mp/assets/imgs/facebox/58.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=59;
        $face->mark = '[乒乓]';
        $face->url = 'mp/assets/imgs/facebox/59.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=60;
        $face->mark = '[咖啡]';
        $face->url = 'mp/assets/imgs/facebox/60.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=61;
        $face->mark = '[饭]';
        $face->url = 'mp/assets/imgs/facebox/61.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=62;
        $face->mark = '[猪头]';
        $face->url = 'mp/assets/imgs/facebox/62.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=63;
        $face->mark = '[玫瑰]';
        $face->url = 'mp/assets/imgs/facebox/63.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=64;
        $face->mark = '[凋谢]';
        $face->url = 'mp/assets/imgs/facebox/64.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=65;
        $face->mark = '[示爱]';
        $face->url = 'mp/assets/imgs/facebox/65.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=66;
        $face->mark = '[爱心]';
        $face->url = 'mp/assets/imgs/facebox/66.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=67;
        $face->mark = '[心碎]';
        $face->url = 'mp/assets/imgs/facebox/67.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=68;
        $face->mark = '[蛋糕]';
        $face->url = 'mp/assets/imgs/facebox/68.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=69;
        $face->mark = '[闪电]';
        $face->url = 'mp/assets/imgs/facebox/69.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=70;
        $face->mark = '[炸弹]';
        $face->url = 'mp/assets/imgs/facebox/70.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=71;
        $face->mark = '[刀]';
        $face->url = 'mp/assets/imgs/facebox/71.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=72;
        $face->mark = '[足球]';
        $face->url = 'mp/assets/imgs/facebox/72.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=73;
        $face->mark = '[瓢虫]';
        $face->url = 'mp/assets/imgs/facebox/73.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=74;
        $face->mark = '[便便]';
        $face->url = 'mp/assets/imgs/facebox/74.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=75;
        $face->mark = '[月亮]';
        $face->url = 'mp/assets/imgs/facebox/75.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=76;
        $face->mark = '[太阳]';
        $face->url = 'mp/assets/imgs/facebox/76.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=77;
        $face->mark = '[礼物]';
        $face->url = 'mp/assets/imgs/facebox/77.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=78;
        $face->mark = '[拥抱]';
        $face->url = 'mp/assets/imgs/facebox/78.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=79;
        $face->mark = '[强]';
        $face->url = 'mp/assets/imgs/facebox/79.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=80;
        $face->mark = '[弱]';
        $face->url = 'mp/assets/imgs/facebox/80.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=81;
        $face->mark = '[握手]';
        $face->url = 'mp/assets/imgs/facebox/81.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=82;
        $face->mark = '[胜利]';
        $face->url = 'mp/assets/imgs/facebox/82.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=83;
        $face->mark = '[抱拳]';
        $face->url = 'mp/assets/imgs/facebox/83.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=84;
        $face->mark = '[勾引]';
        $face->url = 'mp/assets/imgs/facebox/84.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=85;
        $face->mark = '[拳头]';
        $face->url = 'mp/assets/imgs/facebox/85.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=86;
        $face->mark = '[差劲]';
        $face->url = 'mp/assets/imgs/facebox/86.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=87;
        $face->mark = '[爱你]';
        $face->url = 'mp/assets/imgs/facebox/87.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=88;
        $face->mark = '[NO]';
        $face->url = 'mp/assets/imgs/facebox/88.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=89;
        $face->mark = '[OK]';
        $face->url = 'mp/assets/imgs/facebox/89.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=90;
        $face->mark = '[爱情]';
        $face->url = 'mp/assets/imgs/facebox/90.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=91;
        $face->mark = '[飞吻]';
        $face->url = 'mp/assets/imgs/facebox/91.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=92;
        $face->mark = '[跳跳]';
        $face->url = 'mp/assets/imgs/facebox/92.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=93;
        $face->mark = '[发抖]';
        $face->url = 'mp/assets/imgs/facebox/93.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=94;
        $face->mark = '[呕火]';
        $face->url = 'mp/assets/imgs/facebox/94.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=95;
        $face->mark = '[转圈]';
        $face->url = 'mp/assets/imgs/facebox/95.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=96;
        $face->mark = '[磕头]';
        $face->url = 'mp/assets/imgs/facebox/96.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=97;
        $face->mark = '[回头]';
        $face->url = 'mp/assets/imgs/facebox/97.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=98;
        $face->mark = '[跳绳]';
        $face->url = 'mp/assets/imgs/facebox/98.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=99;
        $face->mark = '[挥手]';
        $face->url = 'mp/assets/imgs/facebox/99.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=100;
        $face->mark = '[激动]';
        $face->url = 'mp/assets/imgs/facebox/100.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=101;
        $face->mark = '[街舞]';
        $face->url = 'mp/assets/imgs/facebox/101.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=102;
        $face->mark = '[献吻]';
        $face->url = 'mp/assets/imgs/facebox/102.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=103;
        $face->mark = '[右太极]';
        $face->url = 'mp/assets/imgs/facebox/103.gif';
        array_push($facebox,$face);
        $face = new stdClass();
        $face->id=104;
        $face->mark = '[左太极]';
        $face->url = 'mp/assets/imgs/facebox/104.gif';
        array_push($facebox,$face);
        return $facebox;
    }
    //获取个人详细信息
    public static function getUserInfo($param){
        $cid = Session::$user["customerId"];
        $userId = Session::$user["userId"];
        Session::switchCustomer(0);
        $miuStatistics = M("miu_statistics");
        $aliasNameModel = M('friends_alias');
        $salesourceStatistics = M("salesource_statistics");
        Session::switchCustomer($cid);
        $MiUserModel = M("user");
        $id=$param->id;
        $qid = $param->qid;
        $condition["a.id"] = array("eq",$id);
        $userInfo = $MiUserModel->alias("a")
            ->join("wx_".$cid."_user_weixin_info wei on a.id = wei.userId")
            ->join("wx_quan_user b on a.id=b.uid and b.deleted=0 and b.qid=".$qid)
            ->where($condition)
            ->field("a.phone,a.fullName,b.id as quid,wei.headimgurl as profileUrl,b.createTime,b.miCoins,b.isSaleSource,b.totalRevenue as income,wei.nickname")
            ->find();
        if ($userInfo) {
            $aliasName = $aliasNameModel->where(['userId' => $userId, 'cid' => $cid, 'friendId' => $id])->getField('alias');
            $userInfo['aliasName'] = $aliasName;
        }
        //查询数据看板数据
        if ($userInfo['isSaleSource']){
            $selfData = R('MiYouQuan/StatisData',array($cid, $qid, $id, 2));
        }else{
            $selfData = R('MiYouQuan/StatisData',array($cid, $qid, $id, 1));
        }
        $selfDataInfo = [
            [
                "type" =>1,
                "descript" => '推荐好友',
                "number" => (empty($selfData["friendCount"]) ? 0 : $selfData["friendCount"]). '人'
            ],
            [
                "type" =>2,
                "descript" => '分享浏览人数',
                "number" => (empty($selfData["shareUv"]) ? 0 : $selfData["shareUv"]) . '人'
            ],
            [
                "type" =>3,
                "descript" => '总收入',
                "number" => round($userInfo["income"],2). '元'
            ],
            [
                "type" =>4,
                "descript" => '账户余额',
                "number" =>  round($userInfo["miCoins"],2). '元'
            ],
            [
                "type" =>5,
                "descript" => '普通订单数',
                "number" => (empty($selfData["buyOrderCount"]) ? 0 : $selfData["buyOrderCount"]) . '单'
            ],
            [
                "type" =>6,
                "descript" => '普通订单销售额',
                "number" => (empty($selfData["buyOrderPrice"]) ? 0 : $selfData["buyOrderPrice"]) . '元'
            ],
            [
                "type" =>7,
                "descript" => '积分订单数',
                "number" => (empty($selfData["pointOrderCount"]) ? 0 : $selfData["pointOrderCount"]) . '单'
            ],
            [
                "type" =>8,
                "descript" => '积分订单销售额',
                "number" => (empty($selfData["pointOrderPrice"]) ? 0 : $selfData["pointOrderPrice"]) . '积分'
            ],
            [
                "type" =>9,
                "descript" => '营销订单数',
                "number" => (empty($selfData["formOrderCount"]) ? 0 : $selfData["formOrderCount"]) . '单'
            ],
            [
                "type" =>10,
                "descript" => '营销订单销售额',
                "number" => (empty($selfData["formOrderPrice"]) ? 0 : $selfData["formOrderPrice"]) . '元'
            ],
            [
                "type" =>11,
                "descript" => '分享次数',
                "number" => (empty($selfData["shareCount"]) ? 0 : $selfData["shareCount"]). '次'
            ]

        ];
        if ($userInfo) {
            $return['code'] = 0;
            $return['msg'] = '用户信息展示';
            $return['data'] = $userInfo;
            $return["selfDataInfo"] = $selfDataInfo;
            Output::instance()->object($return);
        } else {
            $return['code'] = 1;
            $return['msg'] = '没有此用户';
            Output::instance()->object($return);
        }
    }
    //删除用户
    public static function deleteQuanUser($param){
        $MiYouQuan = A("MiYouQuan");
        $MiYouQuan->deleteQuanUser($param->id,$param->uid,$param->type);
    }
    //好友列表
    public function friendsList($uid,$qid,$search=null,$register=null,$order=null,$start=0,$limit=10, $excel = 0,$startTime='',$endTime='',$all='',$uids=''){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $aliasModel = M('friends_alias');
        $mimallModel = M("mimall_user");
        $quanUser = M("quan_user");
        $miyouquan = M("miyouquan");
        Session::switchCustomer($customerId);
        $user = M('user');
        $weixin = M('user_weixin_info');
        $quanInfo = $miyouquan->where("id=$qid")->field("refereeAward,parentRefereeAward,cId")->find();
        //如果查询所有用户走if逻辑
        if ($all) {
            $where_friend["mi.qId"] = $qid;
            $where_friend["mi.cId"] = $customerId;
            $where_friend["mi.uId"] = array('IN', $uids);
        }else {
            //判断这个营销圈的设置是几级，进行不同的字段查找
            if($quanInfo['parentRefereeAward']>0){
                $maxLev = 3;
                $where['mi.miUid'] = $uid;
                $where['mi.refereeUid'] = $uid;
                $where['mi.preRefereeUid'] = $uid;
                $where['_logic'] = "OR";
                $where_friend["_complex"] = $where;
            }else if($quanInfo['refereeAward']>0){
                $maxLev = 2;
                $where['mi.miUid'] = $uid;
                $where['mi.refereeUid'] = $uid;
                $where['_logic'] = "OR";
                $where_friend["_complex"] = $where;
            }else{
                $maxLev = 1;
                $where_friend['mi.miUid'] = $uid;
            }
            $where_friend["mi.qId"] = $qid;
            $where_friend["mi.uId"] = array('neq', $uid);
            $where_friend["mi.cId"] = $customerId;
        }

        //增加好友的注册情况筛选
        $strSql = '';
        if ($register == 'yes'){
            $sql = "mi.uId = mi.miUid";
            $strSql .= $sql;
        }else if ($register == 'no'){
            $sql = "mi.uId <> mi.miUid";
            $strSql .= $sql;
        }
        //增加排序条件
        if (empty($order) || ($order == 'time')){
            $order = 'mi.createTime desc';
        }else{
            if ($order == 'people'){
                $order = 'st.friendCount desc';
            }else if ($order == 'share'){
                $order = 'st.shareUv desc';
            }else if ($order == 'order'){
                $order = 'st.orderCount desc';
            }
        }
        //增加时间筛选
        if ($startTime != '' && $endTime != '') {
            $where_friend['mi.createTime'] = array(array('egt', $startTime), array('elt', date('Y-m-d', strtotime("$endTime +1 day"))));
        } else if ($startTime != '') {
            $where_friend['mi.createTime'] = array('egt', $startTime);
        } else if ($endTime != '') {
            $where_friend['mi.createTime'] = array('elt', date('Y-m-d', strtotime("$endTime +1 day")));
        }
        //增加搜索条件
        if (!empty($search)){
            if (!empty($strSql)){
                $sql = ' AND';
            }else{
                $sql = '';
            }
            $sql .= ' ( us.fullName LIKE  "%' . $search . '%" ) OR (wei.nickname LIKE "%' .  $search . '%") OR ( us.phone LIKE "%' . $search . '%")';
            $strSql .= $sql;
        }
        // 最后拼接SQL
        if (!empty($strSql)) {
            $where_friend['_string'] = $strSql;
        }
        //获取数目
        $friendsCount = $mimallModel->alias("mi")
            ->join("wx_quan_user qu on mi.uId = qu.uid and qu.qid =".$qid." and qu.deleted=0")
            ->join("wx_".$customerId."_user us on mi.uId = us.id")
            ->join("wx_".$customerId."_user_weixin_info wei on mi.uId = wei.userId")
            ->join("wx_miu_statistics st on mi.uId = st.uid and st.cid=".$customerId)
            ->where($where_friend)
            ->count();
        //获取信息
        if ($excel){
            $friendsInfo = $mimallModel->alias("mi")
                ->join("wx_quan_user qu on mi.uId = qu.uid and qu.qid =".$qid." and qu.deleted=0")
                ->join("wx_".$customerId."_user us on mi.uId = us.id")
                ->join("wx_".$customerId."_user_weixin_info wei on mi.uId = wei.userId")
                ->join("wx_miu_statistics st on mi.uId = st.uid and st.cid=".$customerId)
                ->where($where_friend)
                ->order($order)
                ->field("us.phone, us.email, us.birthday, wei.province,mi.refereeUid as upRefereeUid,mi.miUid,qu.id as quid,us.fullName,mi.uId as uid,wei.headimgurl as profileUrl,us.status,wei.nickname,mi.createTime,mi.openid")
                ->select();
        }else {
            $friendsInfo = $mimallModel->alias("mi")
                ->join("wx_quan_user qu on mi.uId = qu.uid and qu.qid =".$qid." and qu.deleted=0")
                ->join("wx_".$customerId."_user us on mi.uId = us.id")
                ->join("wx_".$customerId."_user_weixin_info wei on mi.uId = wei.userId")
                ->join("wx_miu_statistics st on mi.uId = st.uid and st.cid=".$customerId)
                ->where($where_friend)
                ->order($order)
                ->field("us.phone, us.email, us.birthday, wei.province,mi.refereeUid as upRefereeUid,mi.miUid,qu.id as quid,us.fullName,mi.uId as uid,wei.headimgurl as profileUrl,us.status,wei.nickname,mi.createTime,mi.openid")
                ->limit($start,$limit)
                ->select();
        }

        //获取上级推荐人信息
        if (!empty($friendsInfo)){
            foreach ($friendsInfo as $key=>$value) {
                if ($value['quid']){
                    $where_referee['userId'] = $value['upRefereeUid'];
                    $statisData = R('MiYouQuan/StatisData',array($customerId,$qid,$value['uid'],1));
                    $friendsInfo[$key]['statisData'] = $statisData;
                }else{
                    $where_referee['userId'] = $value['miUid'];
                    $friendsInfo[$key]['upRefereeUid'] = $value['miUid'];
                    $friendsInfo[$key]['statisData'] = [];
                }
                $friendsInfo[$key]['birthday'] = date('Y-m-d', strtotime($value['birthday']));
                //$where_referee['qid'] = $qid;
                //$where_referee['deleted'] = 0;
                //$friendsInfo[$key]['refereeInfo'] = $quanUser->where($where_referee)->getField("nickName");
                $friendsInfo[$key]['refereeInfo'] = $weixin->where($where_referee)->getField("nickname");
                //插入备注名称
                $aliasName = $aliasModel->where(['cid' => $customerId, 'userId' => $uid, 'friendId' => $value['uid']])->getField('alias');
                $friendsInfo[$key]['aliasName'] = $aliasName;
            }
        }
        if ($excel) {
            self::friendListExcel($friendsInfo);
            return;
        }
        //输出好友列表
        Output::instance()->object([
            'code'=>0,
            'msg'=>'好友列表返回',
            'data'=>$friendsInfo,
            'total'=>$friendsCount
        ]);

    }

    private static function friendListExcel($friendsInfo)
    {
        foreach ($friendsInfo as $key => $val) {
            switch ($val['status']) {
                case 'subscribe':
                    $friendsInfo[$key]['status'] = '已关注';
                    break;
                case 'unsubscribe' :
                    $friendsInfo[$key]['status'] = '未关注';
                    break;
                case 'sharesubscribe':
                    $friendsInfo[$key]['status'] = '分享关注';
                    break;
                default:
                    break;
            }
            if ($val['quid']) {
                    $friendsInfo[$key]['register'] = '已注册';
            }else {
                    $friendsInfo[$key]['register'] = '未注册';
            }
            $friendsInfo[$key]['shareUv'] = empty($val['statisData']['shareUv'])? 0 : $val['statisData']['shareUv'];
            $friendsInfo[$key]['miuCount'] = empty($val['statisData']['miuCount'])? 0 : $val['statisData']['miuCount'];
            $friendsInfo[$key]['formOrderCount'] = empty($val['statisData']['formOrderCount'])? 0 : $val['statisData']['formOrderCount'];
            $friendsInfo[$key]['buyOrderCount'] = empty($val['statisData']['buyOrderCount'])? 0 : $val['statisData']['buyOrderCount'];
        }
        $expCellName = [
            //rray('nickname', '用户名'),
            array('fullName', '姓名'),
            array('phone', '手机号'),
            //array('email', '邮箱'),
            //array('province', '所在地'),
           // array('birthday', '生日'),
            array('status', '状态'),
            array('register', '类型'),
            array('shareUv', '分享浏览人数'),
            array('miuCount', '注册好友数	'),
            array('formOrderCount', '营销订单数'),
            array('buyOrderCount', '普通订单数'),
            array('createTime', '创建时间')
        ];

        $name = '好友列表导出';
        Output::instance()->objArrayExcel($name, $expCellName, $friendsInfo);
    }
    //h获得签名信息
    public static function getSignPackage($param){
        $url = $param->url;
        $pkg=WeixinApi::getSignPackage($url);
        //输出签名信息
        Output::instance()->object([
            'code'=>0,
            'msg'=>'输出签名信息',
            'data'=>$pkg
        ]);

    }

    //删除用户
    public static function userActionList($param){
        $MiYouQuan = A("MiYouQuan");
        $MiYouQuan->userActionList($param->uid,$param->customerId,$param->start,$param->limit);
    }

    /**
     * 定义英孚数据
     * @param $cid /customerId
     * @return array
     */
    public function efDataArr($cid){
        $efDataArr = [
            52=>[       //外侧
                ['contentId'=>587,'backImg'=>'http://oss.mboxone.com/20180720/image/50/1532091487500883.jpg',
                    'position'=>['x'=>607,'y'=>57],'size'=>['w'=>200, 'h'=>200],'type'=>1,
                    'url'=>'http://wx532fcc9ce21e7957.wxtest.mboxone.com/test/call.html?module=micontent&method=getMiContentDetail&'],
                ['contentId'=>586,'backImg'=>'http://oss.mboxone.com/20180408/image/50/1523180040499236.jpg',
                    'position'=>['x'=>'740','y'=>'43'],'size'=>['w'=>220, 'h'=>220],'type'=>1,
                    'url'=>'http://wx532fcc9ce21e7957.wxtest.mboxone.com/test/call.html?module=micontent&method=getMiContentDetail&']
            ],
            50=>[       //内测
                ['contentId'=>7356,'backImg'=>'http://oss.mboxone.com/20180705/image/50/1530776208333682.jpg',
                    'position'=>['x'=>730,'y'=>750],'size'=>['w'=>200, 'h'=>200],'type'=>1,
                    'url'=>'http://newtest.mboxone.com/test/call.html?module=micontent&method=getMiContentDetail&'],
                ['contentId'=>7260,'backImg'=>'http://oss.mboxone.com/20180705/image/50/1530776231661672.jpg',
                    'position'=>['x'=>730,'y'=>750],'size'=>['w'=>200, 'h'=>200],'type'=>1,
                    'url'=>'http://newtest.mboxone.com/test/call.html?module=micontent&method=getMiContentDetail&'],
                ['contentId'=>481,'backImg'=>'http://oss.mboxone.com/20180705/image/50/1530776255565839.jpg',
                    'position'=>['x'=>730,'y'=>750],'size'=>['w'=>200, 'h'=>200],'type'=>1,
                    'url'=>'http://newtest.mboxone.com/test/call.html?module=micontent&method=getMiContentDetail&']
            ],
            117=>[      //正式
                ['contentId'=>8465,'backImg'=>'http://oss.mboxone.com/20180720/image/50/1532091487500883.jpg',
                    'position'=>['x'=>607,'y'=>57],'size'=>['w'=>200, 'h'=>200],'type'=>1,
                    'url'=>'http://wx9db859ac98c33a73.wx.mboxone.com/wx/call.html?module=micontent&method=getMiContentDetail&'],
                ['contentId'=>8415,'backImg'=>'http://oss.mboxone.com/20180717/image/52/1531807488553388.jpg',
                    'position'=>['x'=>'607','y'=>'57'],'size'=>['w'=>200, 'h'=>200],'type'=>1,
                    'url'=>'http://wx9db859ac98c33a73.wx.mboxone.com/wx/call.html?module=micontent&method=getMiContentDetail&'],
                ['contentId'=>8253,'backImg'=>'http://oss.mboxone.com/20180719/image/52/1531987422245919.jpg',
                    'position'=>['x'=>730,'y'=>750],'size'=>['w'=>200, 'h'=>200],'type'=>1,
                    'url'=>'http://wx9db859ac98c33a73.wx.mboxone.com/wx/call.html?module=micontent&method=getMiContentDetail&'],
                ['contentId'=>8255,'backImg'=>'http://oss.mboxone.com/20180705/image/50/1530776208333682.jpg',
                    'position'=>['x'=>730,'y'=>750],'size'=>['w'=>200, 'h'=>200],'type'=>1,
                    'url'=>'http://wx9db859ac98c33a73.wx.mboxone.com/wx/call.html?module=micontent&method=getMiContentDetail&']
            ],
            147=>[      //正式
                ['contentId'=>6611,'backImg'=>'http://oss.mboxone.com/20180427/image/50/1524795798682289.jpg',
                    'position'=>['x'=>785,'y'=>1325],'size'=>['w'=>180, 'h'=>180],'type'=>1,
                    'url'=>'http://wx520db2458ce89bd6.wx.mboxone.com/wx/call.html?module=micontent&method=getMiContentDetail&']
            ],
            172=>[      //正式
                ['contentId'=>8214,'backImg'=>'http://oss.mboxone.com/20180718/image/50/1531900515523136.jpg',
                    'position'=>['x'=>375,'y'=>637],'size'=>['w'=>180, 'h'=>180],'type'=>1,
                    'url'=>'http://wx8a294c7b1481e664.wx.mboxone.com/wx/call.html?module=micontent&method=getMiContentDetail&']
            ]
        ];
        return $efDataArr[$cid];
    }

    /**
     * 使用临时海报账号集合
     * @return array
     */
    public function temporaryPoster(){
        return [50,117,147,52,172];
    }
    /**
     * 英孚创建多张海报
     * @param $fileName     //保存的文件名
     * @param $qrImg        //二维码文件
     * @param $backGroudImg //背景图片
     * @param $position     //二维码位置
     * @param $size         //二维码大小
     * @param $customerId   //cid
     * @return object||null
     */
    public function createMoreImg($fileName,$qrImg,$backGroudImg,$position,$size,$customerId)
    {
        $fname="vendor_$fileName.png";
        $fileName=LOCAL_PIC_PATH . "$fname";
        $img=self::curls($backGroudImg);

        $img=imagecreatefromstring($img);
        if(!$img) {
            $out1 = new stdClass();
            $out1->code=1;
            $out1->msg="背景图片获取错误，请重试";
            return $out1;
        }
        $imgWidth=imagesx($img);
        $imgHeight=imagesy($img);
        $qrImg = imagecreatefrompng($qrImg);
        if(!$qrImg) {
            $out1=new StdClass();
            $out1->code=1;
            $out1->msg="二维码生成错误，请重试";
            return $out1;
        }
        $qrImgWidth=imagesx($qrImg);
        $qrImgHeight=imagesy($qrImg);
        if($size){
            $sizeW = $size['w'];
            $sizeH = $size['h'];
        }else{
            $sizeW=220;
            $sizeH=220;
        }
        if($position){
            $qrImgLeft = $position['x'];
            $qrImgTop = $position['y'];
        }else{
            $qrImgLeft = $imgWidth/2-110;
            $qrImgTop = $imgHeight/2-110;
        }
        imagecopyresampled($img,$qrImg,$qrImgLeft,$qrImgTop,0,0,$sizeW,$sizeH,$qrImgWidth,$qrImgHeight);
        imagejpeg($img,$fileName);
        imagedestroy($img);
        if(file_exists($fileName)){
            $out=R("Upload/uploadLocalFileToOss",array($fname,$fileName));
            @unlink($fileName);
            if(!$out->code){
                return $out;
            }else{
                $outError = new stdClass();
                $outError->code = 1;
                $outError->msg = '上传oss失败';
                return $outError;
            }
        }
        $outError = new stdClass();
        $outError->code = 1;
        $outError->msg = '海报生成失败';
        return $outError;
    }

    /**
     * 保存用户点击联系区信息
     * @param $param /参数
     */
    function saveClickContact($param)
    {
        $cid = Session::$user['customerId'];
        $data = [];
        $data['uid'] = Session::$user['userId'];
        Session::switchCustomer(0);
        $contactClick_tab = M('contact_click_info');
        $quanUser_tab = M('quan_user');
        Session::switchCustomer($cid);
        $data['cid'] = $cid;
        $data['qid'] = $param->qid;
        $data['miUid'] = $param->miUid;
        $data['module'] = $param->module;
        $data['moduleId'] = $param->moduleId;
        $data['type'] = $param->type;
        $data['title'] = $param->title;
        $data['content'] = $param->content;
        $data['saleSource'] = $quanUser_tab->where(['uid'=>$data['miUid'], 'qid'=>$data['qid'], 'deleted'=>0])->getField('saleSource');
        $data['createTime'] = $data['updateTime'] = date('Y-m-d H:i:s');
        $ret = $contactClick_tab->add($data);
        if(!$ret){
            Log::write('保存contact信息失败sql:'.$quanUser_tab->getLastSql());
            Output::instance()->resultCode(code_sql_error);
            return;
        }
        Output::instance()->resultCode();
    }

    public function getPoster($module, $moduleId)
    {
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $posterModel = M("poster");
        Session::switchCustomer($customerId);
        if (empty($module) && empty($moduleId)) {
            $where['cid'] = array('eq', $customerId);
            $where['deleted'] = array('eq', 0);
            $where['status'] = array('eq', 1);
            $where['isJoinQuan'] = array('eq', 1);
            $posterData = $posterModel->where($where)->select();
        } elseif ($module == 'product' || $module == 'micontent') {
            $where['cid'] = array('eq', $customerId);
            $where['deleted'] = array('eq', 0);
            $where['status'] = array('eq', 1);
            $where['module'] = array('eq', $module);
            $where['moduleId'] = array('eq', $moduleId);
            $posterData = $posterModel->where($where)->select();
        }

        return $posterData;
    }
    public static function setFriendNameAlias($friendId, $alias){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        $userId = Session::$user['userId'];
        Session::switchCustomer(0);
        $friendAliasModel = M('friends_alias');
        Session::switchCustomer($customerId);

        $data['alias'] = $alias;
        $record = $friendAliasModel->where(['cid' => $customerId, 'userId' => $userId, 'friendId' => $friendId])->find();
        if (empty($record)) {
            $data['cid'] = $customerId;
            $data['userId'] = $userId;
            $data['friendId'] = $friendId;
            $res = $friendAliasModel->add($data);
        } else {
            $res = $friendAliasModel->where(['id' => $record['id']])->save($data);
        }

        if (is_numeric($res)) {
            Output::instance()->object([
                'code' => 0,
                'msg' => 'ok'
            ]);
        } else {
            Output::instance()->object([
                'code' => 1,
                'msg' => '失败'
            ]);
        }

    }

    public function qrcodeConfig($backUrl,$location,$size){
        $imgInfo = getimagesize($backUrl);
        $imgWidth = $imgInfo[0];
        $arr['location']['x'] = $location[0]/375*$imgWidth;
        $arr['location']['y'] = $location[1]/375*$imgWidth;
        $arr['size']['w'] = $size[0]/375*$imgWidth;
        $arr['size']['h'] = $size[1]/375*$imgWidth;
        return $arr;
    }
}
